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