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 Note: Version Strings (v-strings) have been deprecated. They will be
346 removed in some future release after Perl 5.8.1. The marginal benefits
347 of v-strings were greatly outweighed by the potential for Surprise and
348 Confusion.
349
350 A literal of the form "v1.20.300.4000" is parsed as a string composed
351 of characters with the specified ordinals. This form, known as
352 v-strings, provides an alternative, more readable way to construct
353 strings, rather than use the somewhat less readable interpolation form
354 "\x{1}\x{14}\x{12c}\x{fa0}". This is useful for representing Unicode
355 strings, and for comparing version "numbers" using the string
356 comparison operators, "cmp", "gt", "lt" etc. If there are two or more
357 dots in the literal, the leading "v" may be omitted.
358
359 print v9786; # prints SMILEY, "\x{263a}"
360 print v102.111.111; # prints "foo"
361 print 102.111.111; # same
362
363 Such literals are accepted by both "require" and "use" for doing a
364 version check. Note that using the v-strings for IPv4 addresses is not
365 portable unless you also use the inet_aton()/inet_ntoa() routines of
366 the Socket package.
367
368 Note that since Perl 5.8.1 the single-number v-strings (like "v65") are
369 not v-strings before the "=>" operator (which is usually used to
370 separate a hash key from a hash value), instead they are interpreted as
371 literal strings ('v65'). They were v-strings from Perl 5.6.0 to Perl
372 5.8.0, but that caused more confusion and breakage than good. Multi-
373 number v-strings like "v65.66" and 65.66.67 continue to be v-strings
374 always.
375
376 Special Literals
377
378 The special literals __FILE__, __LINE__, and __PACKAGE__ represent the
379 current filename, line number, and package name at that point in your
380 program. They may be used only as separate tokens; they will not be
381 interpolated into strings. If there is no current package (due to an
382 empty "package;" directive), __PACKAGE__ is the undefined value.
383
384 The two control characters ^D and ^Z, and the tokens __END__ and
385 __DATA__ may be used to indicate the logical end of the script before
386 the actual end of file. Any following text is ignored.
387
388 Text after __DATA__ may be read via the filehandle "PACKNAME::DATA",
389 where "PACKNAME" is the package that was current when the __DATA__
390 token was encountered. The filehandle is left open pointing to the
391 contents after __DATA__. It is the program's responsibility to "close
392 DATA" when it is done reading from it. For compatibility with older
393 scripts written before __DATA__ was introduced, __END__ behaves like
394 __DATA__ in the top level script (but not in files loaded with
395 "require" or "do") and leaves the remaining contents of the file
396 accessible via "main::DATA".
397
398 See SelfLoader for more description of __DATA__, and an example of its
399 use. Note that you cannot read from the DATA filehandle in a BEGIN
400 block: the BEGIN block is executed as soon as it is seen (during
401 compilation), at which point the corresponding __DATA__ (or __END__)
402 token has not yet been seen.
403
404 Barewords
405
406 A word that has no other interpretation in the grammar will be treated
407 as if it were a quoted string. These are known as "barewords". As
408 with filehandles and labels, a bareword that consists entirely of
409 lowercase letters risks conflict with future reserved words, and if you
410 use the "use warnings" pragma or the -w switch, Perl will warn you
411 about any such words. Perl limits barewords (like identifiers) to
412 about 250 characters. Future versions of Perl are likely to eliminate
413 these arbitrary limitations.
414
415 Some people may wish to outlaw barewords entirely. If you say
416
417 use strict 'subs';
418
419 then any bareword that would NOT be interpreted as a subroutine call
420 produces a compile-time error instead. The restriction lasts to the
421 end of the enclosing block. An inner block may countermand this by
422 saying "no strict 'subs'".
423
424 Array Joining Delimiter
425
426 Arrays and slices are interpolated into double-quoted strings by
427 joining the elements with the delimiter specified in the $" variable
428 ($LIST_SEPARATOR if "use English;" is specified), space by default.
429 The following are equivalent:
430
431 $temp = join($", @ARGV);
432 system "echo $temp";
433
434 system "echo @ARGV";
435
436 Within search patterns (which also undergo double-quotish substitution)
437 there is an unfortunate ambiguity: Is "/$foo[bar]/" to be interpreted
438 as "/${foo}[bar]/" (where "[bar]" is a character class for the regular
439 expression) or as "/${foo[bar]}/" (where "[bar]" is the subscript to
440 array @foo)? If @foo doesn't otherwise exist, then it's obviously a
441 character class. If @foo exists, Perl takes a good guess about
442 "[bar]", and is almost always right. If it does guess wrong, or if
443 you're just plain paranoid, you can force the correct interpretation
444 with curly braces as above.
445
446 If you're looking for the information on how to use here-documents,
447 which used to be here, that's been moved to "Quote and Quote-like
448 Operators" in perlop.
449
450 List value constructors
451 List values are denoted by separating individual values by commas (and
452 enclosing the list in parentheses where precedence requires it):
453
454 (LIST)
455
456 In a context not requiring a list value, the value of what appears to
457 be a list literal is simply the value of the final element, as with the
458 C comma operator. For example,
459
460 @foo = ('cc', '-E', $bar);
461
462 assigns the entire list value to array @foo, but
463
464 $foo = ('cc', '-E', $bar);
465
466 assigns the value of variable $bar to the scalar variable $foo. Note
467 that the value of an actual array in scalar context is the length of
468 the array; the following assigns the value 3 to $foo:
469
470 @foo = ('cc', '-E', $bar);
471 $foo = @foo; # $foo gets 3
472
473 You may have an optional comma before the closing parenthesis of a list
474 literal, so that you can say:
475
476 @foo = (
477 1,
478 2,
479 3,
480 );
481
482 To use a here-document to assign an array, one line per element, you
483 might use an approach like this:
484
485 @sauces = <<End_Lines =~ m/(\S.*\S)/g;
486 normal tomato
487 spicy tomato
488 green chile
489 pesto
490 white wine
491 End_Lines
492
493 LISTs do automatic interpolation of sublists. That is, when a LIST is
494 evaluated, each element of the list is evaluated in list context, and
495 the resulting list value is interpolated into LIST just as if each
496 individual element were a member of LIST. Thus arrays and hashes lose
497 their identity in a LIST--the list
498
499 (@foo,@bar,&SomeSub,%glarch)
500
501 contains all the elements of @foo followed by all the elements of @bar,
502 followed by all the elements returned by the subroutine named SomeSub
503 called in list context, followed by the key/value pairs of %glarch. To
504 make a list reference that does NOT interpolate, see perlref.
505
506 The null list is represented by (). Interpolating it in a list has no
507 effect. Thus ((),(),()) is equivalent to (). Similarly, interpolating
508 an array with no elements is the same as if no array had been
509 interpolated at that point.
510
511 This interpolation combines with the facts that the opening and closing
512 parentheses are optional (except when necessary for precedence) and
513 lists may end with an optional comma to mean that multiple commas
514 within lists are legal syntax. The list "1,,3" is a concatenation of
515 two lists, "1," and 3, the first of which ends with that optional
516 comma. "1,,3" is "(1,),(3)" is "1,3" (And similarly for "1,,,3" is
517 "(1,),(,),3" is "1,3" and so on.) Not that we'd advise you to use this
518 obfuscation.
519
520 A list value may also be subscripted like a normal array. You must put
521 the list in parentheses to avoid ambiguity. For example:
522
523 # Stat returns list value.
524 $time = (stat($file))[8];
525
526 # SYNTAX ERROR HERE.
527 $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES
528
529 # Find a hex digit.
530 $hexdigit = ('a','b','c','d','e','f')[$digit-10];
531
532 # A "reverse comma operator".
533 return (pop(@foo),pop(@foo))[0];
534
535 Lists may be assigned to only when each element of the list is itself
536 legal to assign to:
537
538 ($a, $b, $c) = (1, 2, 3);
539
540 ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
541
542 An exception to this is that you may assign to "undef" in a list. This
543 is useful for throwing away some of the return values of a function:
544
545 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
546
547 List assignment in scalar context returns the number of elements
548 produced by the expression on the right side of the assignment:
549
550 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
551 $x = (($foo,$bar) = f()); # set $x to f()'s return count
552
553 This is handy when you want to do a list assignment in a Boolean
554 context, because most list functions return a null list when finished,
555 which when assigned produces a 0, which is interpreted as FALSE.
556
557 It's also the source of a useful idiom for executing a function or
558 performing an operation in list context and then counting the number of
559 return values, by assigning to an empty list and then using that
560 assignment in scalar context. For example, this code:
561
562 $count = () = $string =~ /\d+/g;
563
564 will place into $count the number of digit groups found in $string.
565 This happens because the pattern match is in list context (since it is
566 being assigned to the empty list), and will therefore return a list of
567 all matching parts of the string. The list assignment in scalar context
568 will translate that into the number of elements (here, the number of
569 times the pattern matched) and assign that to $count. Note that simply
570 using
571
572 $count = $string =~ /\d+/g;
573
574 would not have worked, since a pattern match in scalar context will
575 only return true or false, rather than a count of matches.
576
577 The final element of a list assignment may be an array or a hash:
578
579 ($a, $b, @rest) = split;
580 my($a, $b, %rest) = @_;
581
582 You can actually put an array or hash anywhere in the list, but the
583 first one in the list will soak up all the values, and anything after
584 it will become undefined. This may be useful in a my() or local().
585
586 A hash can be initialized using a literal list holding pairs of items
587 to be interpreted as a key and a value:
588
589 # same as map assignment above
590 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
591
592 While literal lists and named arrays are often interchangeable, that's
593 not the case for hashes. Just because you can subscript a list value
594 like a normal array does not mean that you can subscript a list value
595 as a hash. Likewise, hashes included as parts of other lists
596 (including parameters lists and return lists from functions) always
597 flatten out into key/value pairs. That's why it's good to use
598 references sometimes.
599
600 It is often more readable to use the "=>" operator between key/value
601 pairs. The "=>" operator is mostly just a more visually distinctive
602 synonym for a comma, but it also arranges for its left-hand operand to
603 be interpreted as a string -- if it's a bareword that would be a legal
604 simple identifier ("=>" doesn't quote compound identifiers, that
605 contain double colons). This makes it nice for initializing hashes:
606
607 %map = (
608 red => 0x00f,
609 blue => 0x0f0,
610 green => 0xf00,
611 );
612
613 or for initializing hash references to be used as records:
614
615 $rec = {
616 witch => 'Mable the Merciless',
617 cat => 'Fluffy the Ferocious',
618 date => '10/31/1776',
619 };
620
621 or for using call-by-named-parameter to complicated functions:
622
623 $field = $query->radio_group(
624 name => 'group_name',
625 values => ['eenie','meenie','minie'],
626 default => 'meenie',
627 linebreak => 'true',
628 labels => \%labels
629 );
630
631 Note that just because a hash is initialized in that order doesn't mean
632 that it comes out in that order. See "sort" in perlfunc for examples
633 of how to arrange for an output ordering.
634
635 Subscripts
636 An array is subscripted by specifying a dollar sign ("$"), then the
637 name of the array (without the leading "@"), then the subscript inside
638 square brackets. For example:
639
640 @myarray = (5, 50, 500, 5000);
641 print "The Third Element is", $myarray[2], "\n";
642
643 The array indices start with 0. A negative subscript retrieves its
644 value from the end. In our example, $myarray[-1] would have been 5000,
645 and $myarray[-2] would have been 500.
646
647 Hash subscripts are similar, only instead of square brackets curly
648 brackets are used. For example:
649
650 %scientists =
651 (
652 "Newton" => "Isaac",
653 "Einstein" => "Albert",
654 "Darwin" => "Charles",
655 "Feynman" => "Richard",
656 );
657
658 print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";
659
660 Slices
661 A common way to access an array or a hash is one scalar element at a
662 time. You can also subscript a list to get a single element from it.
663
664 $whoami = $ENV{"USER"}; # one element from the hash
665 $parent = $ISA[0]; # one element from the array
666 $dir = (getpwnam("daemon"))[7]; # likewise, but with list
667
668 A slice accesses several elements of a list, an array, or a hash
669 simultaneously using a list of subscripts. It's more convenient than
670 writing out the individual elements as a list of separate scalar
671 values.
672
673 ($him, $her) = @folks[0,-1]; # array slice
674 @them = @folks[0 .. 3]; # array slice
675 ($who, $home) = @ENV{"USER", "HOME"}; # hash slice
676 ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice
677
678 Since you can assign to a list of variables, you can also assign to an
679 array or hash slice.
680
681 @days[3..5] = qw/Wed Thu Fri/;
682 @colors{'red','blue','green'}
683 = (0xff0000, 0x0000ff, 0x00ff00);
684 @folks[0, -1] = @folks[-1, 0];
685
686 The previous assignments are exactly equivalent to
687
688 ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
689 ($colors{'red'}, $colors{'blue'}, $colors{'green'})
690 = (0xff0000, 0x0000ff, 0x00ff00);
691 ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);
692
693 Since changing a slice changes the original array or hash that it's
694 slicing, a "foreach" construct will alter some--or even all--of the
695 values of the array or hash.
696
697 foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }
698
699 foreach (@hash{qw[key1 key2]}) {
700 s/^\s+//; # trim leading whitespace
701 s/\s+$//; # trim trailing whitespace
702 s/(\w+)/\u\L$1/g; # "titlecase" words
703 }
704
705 A slice of an empty list is still an empty list. Thus:
706
707 @a = ()[1,0]; # @a has no elements
708 @b = (@a)[0,1]; # @b has no elements
709 @c = (0,1)[2,3]; # @c has no elements
710
711 But:
712
713 @a = (1)[1,0]; # @a has two elements
714 @b = (1,undef)[1,0,2]; # @b has three elements
715
716 This makes it easy to write loops that terminate when a null list is
717 returned:
718
719 while ( ($home, $user) = (getpwent)[7,0]) {
720 printf "%-8s %s\n", $user, $home;
721 }
722
723 As noted earlier in this document, the scalar sense of list assignment
724 is the number of elements on the right-hand side of the assignment.
725 The null list contains no elements, so when the password file is
726 exhausted, the result is 0, not 2.
727
728 If you're confused about why you use an '@' there on a hash slice
729 instead of a '%', think of it like this. The type of bracket (square
730 or curly) governs whether it's an array or a hash being looked at. On
731 the other hand, the leading symbol ('$' or '@') on the array or hash
732 indicates whether you are getting back a singular value (a scalar) or a
733 plural one (a list).
734
735 Typeglobs and Filehandles
736 Perl uses an internal type called a typeglob to hold an entire symbol
737 table entry. The type prefix of a typeglob is a "*", because it
738 represents all types. This used to be the preferred way to pass arrays
739 and hashes by reference into a function, but now that we have real
740 references, this is seldom needed.
741
742 The main use of typeglobs in modern Perl is create symbol table
743 aliases. This assignment:
744
745 *this = *that;
746
747 makes $this an alias for $that, @this an alias for @that, %this an
748 alias for %that, &this an alias for &that, etc. Much safer is to use a
749 reference. This:
750
751 local *Here::blue = \$There::green;
752
753 temporarily makes $Here::blue an alias for $There::green, but doesn't
754 make @Here::blue an alias for @There::green, or %Here::blue an alias
755 for %There::green, etc. See "Symbol Tables" in perlmod for more
756 examples of this. Strange though this may seem, this is the basis for
757 the whole module import/export system.
758
759 Another use for typeglobs is to pass filehandles into a function or to
760 create new filehandles. If you need to use a typeglob to save away a
761 filehandle, do it this way:
762
763 $fh = *STDOUT;
764
765 or perhaps as a real reference, like this:
766
767 $fh = \*STDOUT;
768
769 See perlsub for examples of using these as indirect filehandles in
770 functions.
771
772 Typeglobs are also a way to create a local filehandle using the local()
773 operator. These last until their block is exited, but may be passed
774 back. For example:
775
776 sub newopen {
777 my $path = shift;
778 local *FH; # not my!
779 open (FH, $path) or return undef;
780 return *FH;
781 }
782 $fh = newopen('/etc/passwd');
783
784 Now that we have the *foo{THING} notation, typeglobs aren't used as
785 much for filehandle manipulations, although they're still needed to
786 pass brand new file and directory handles into or out of functions.
787 That's because *HANDLE{IO} only works if HANDLE has already been used
788 as a handle. In other words, *FH must be used to create new symbol
789 table entries; *foo{THING} cannot. When in doubt, use *FH.
790
791 All functions that are capable of creating filehandles (open(),
792 opendir(), pipe(), socketpair(), sysopen(), socket(), and accept())
793 automatically create an anonymous filehandle if the handle passed to
794 them is an uninitialized scalar variable. This allows the constructs
795 such as "open(my $fh, ...)" and "open(local $fh,...)" to be used to
796 create filehandles that will conveniently be closed automatically when
797 the scope ends, provided there are no other references to them. This
798 largely eliminates the need for typeglobs when opening filehandles that
799 must be passed around, as in the following example:
800
801 sub myopen {
802 open my $fh, "@_"
803 or die "Can't open '@_': $!";
804 return $fh;
805 }
806
807 {
808 my $f = myopen("</etc/motd");
809 print <$f>;
810 # $f implicitly closed here
811 }
812
813 Note that if an initialized scalar variable is used instead the result
814 is different: "my $fh='zzz'; open($fh, ...)" is equivalent to "open(
815 *{'zzz'}, ...)". "use strict 'refs'" forbids such practice.
816
817 Another way to create anonymous filehandles is with the Symbol module
818 or with the IO::Handle module and its ilk. These modules have the
819 advantage of not hiding different types of the same name during the
820 local(). See the bottom of "open()" in perlfunc for an example.
821
823 See perlvar for a description of Perl's built-in variables and a
824 discussion of legal variable names. See perlref, perlsub, and "Symbol
825 Tables" in perlmod for more discussion on typeglobs and the *foo{THING}
826 syntax.
827
828
829
830perl v5.10.1 2009-06-27 PERLDATA(1)