This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
documentation update from tchrist
[perl5.git] / pod / perldata.pod
CommitLineData
a0d0e21e
LW
1=head1 NAME
2
cb1a09d0 3perldata - Perl data types
a0d0e21e
LW
4
5=head1 DESCRIPTION
6
7=head2 Variable names
8
9Perl has three data structures: scalars, arrays of scalars, and
10associative arrays of scalars, known as "hashes". Normal arrays are
11indexed by number, starting with 0. (Negative subscripts count from
12the end.) Hash arrays are indexed by string.
13
b88cefa9 14Values are usually referred to by name (or through a named reference).
15The first character of the name tells you to what sort of data
16structure it refers. The rest of the name tells you the particular
17value to which it refers. Most often, it consists of a single
18I<identifier>, that is, a string beginning with a letter or underscore,
19and containing letters, underscores, and digits. In some cases, it
20may be a chain of identifiers, separated by C<::> (or by C<'>, but
21that's deprecated); all but the last are interpreted as names of
5f05dabc 22packages, to locate the namespace in which to look
b88cefa9 23up the final identifier (see L<perlmod/Packages> for details).
184e9718 24It's possible to substitute for a simple identifier an expression
5a964f20 25that produces a reference to the value at runtime; this is
b88cefa9 26described in more detail below, and in L<perlref>.
27
28There are also special variables whose names don't follow these
29rules, so that they don't accidentally collide with one of your
5a964f20 30normal variables. Strings that match parenthesized parts of a
b88cefa9 31regular expression are saved under names containing only digits after
32the C<$> (see L<perlop> and L<perlre>). In addition, several special
5a964f20 33variables that provide windows into the inner working of Perl have names
b88cefa9 34containing punctuation characters (see L<perlvar>).
35
a0d0e21e
LW
36Scalar values are always named with '$', even when referring to a scalar
37that is part of an array. It works like the English word "the". Thus
38we have:
39
40 $days # the simple scalar value "days"
41 $days[28] # the 29th element of array @days
42 $days{'Feb'} # the 'Feb' value from hash %days
43 $#days # the last index of array @days
44
45but entire arrays or array slices are denoted by '@', which works much like
46the word "these" or "those":
47
48 @days # ($days[0], $days[1],... $days[n])
49 @days[3,4,5] # same as @days[3..5]
50 @days{'a','c'} # same as ($days{'a'},$days{'c'})
51
52and entire hashes are denoted by '%':
53
54 %days # (key1, val1, key2, val2 ...)
55
56In addition, subroutines are named with an initial '&', though this is
57optional when it's otherwise unambiguous (just as "do" is often
58redundant in English). Symbol table entries can be named with an
59initial '*', but you don't really care about that yet.
60
61Every variable type has its own namespace. You can, without fear of
62conflict, use the same name for a scalar variable, an array, or a hash
63(or, for that matter, a filehandle, a subroutine name, or a label).
64This means that $foo and @foo are two different variables. It also
748a9306 65means that C<$foo[1]> is a part of @foo, not a part of $foo. This may
a0d0e21e
LW
66seem a bit weird, but that's okay, because it is weird.
67
5f05dabc 68Because variable and array references always start with '$', '@', or '%',
a0d0e21e
LW
69the "reserved" words aren't in fact reserved with respect to variable
70names. (They ARE reserved with respect to labels and filehandles,
71however, which don't have an initial special character. You can't have
72a filehandle named "log", for instance. Hint: you could say
73C<open(LOG,'logfile')> rather than C<open(log,'logfile')>. Using uppercase
74filehandles also improves readability and protects you from conflict
5f05dabc 75with future reserved words.) Case I<IS> significant--"FOO", "Foo", and
a0d0e21e
LW
76"foo" are all different names. Names that start with a letter or
77underscore may also contain digits and underscores.
78
79It is possible to replace such an alphanumeric name with an expression
80that returns a reference to an object of that type. For a description
81of this, see L<perlref>.
82
5f05dabc 83Names that start with a digit may contain only more digits. Names
5a964f20 84that do not start with a letter, underscore, or digit are limited to
5f05dabc 85one character, e.g., C<$%> or C<$$>. (Most of these one character names
cb1a09d0 86have a predefined significance to Perl. For instance, C<$$> is the
a0d0e21e
LW
87current process id.)
88
89=head2 Context
90
91The interpretation of operations and values in Perl sometimes depends
92on the requirements of the context around the operation or value.
93There are two major contexts: scalar and list. Certain operations
94return list values in contexts wanting a list, and scalar values
95otherwise. (If this is true of an operation it will be mentioned in
96the documentation for that operation.) In other words, Perl overloads
97certain operations based on whether the expected return value is
98singular or plural. (Some words in English work this way, like "fish"
99and "sheep".)
100
101In a reciprocal fashion, an operation provides either a scalar or a
102list context to each of its arguments. For example, if you say
103
104 int( <STDIN> )
105
184e9718 106the integer operation provides a scalar context for the E<lt>STDINE<gt>
a0d0e21e
LW
107operator, which responds by reading one line from STDIN and passing it
108back to the integer operation, which will then find the integer value
109of that line and return that. If, on the other hand, you say
110
111 sort( <STDIN> )
112
184e9718 113then the sort operation provides a list context for E<lt>STDINE<gt>, which
a0d0e21e
LW
114will proceed to read every line available up to the end of file, and
115pass that list of lines back to the sort routine, which will then
116sort those lines and return them as a list to whatever the context
117of the sort was.
118
119Assignment is a little bit special in that it uses its left argument to
120determine the context for the right argument. Assignment to a scalar
121evaluates the righthand side in a scalar context, while assignment to
122an array or array slice evaluates the righthand side in a list
123context. Assignment to a list also evaluates the righthand side in a
124list context.
125
126User defined subroutines may choose to care whether they are being
127called in a scalar or list context, but most subroutines do not
128need to care, because scalars are automatically interpolated into
129lists. See L<perlfunc/wantarray>.
130
131=head2 Scalar values
132
4633a7c4 133All data in Perl is a scalar or an array of scalars or a hash of scalars.
a0d0e21e 134Scalar variables may contain various kinds of singular data, such as
4633a7c4
LW
135numbers, strings, and references. In general, conversion from one form to
136another is transparent. (A scalar may not contain multiple values, but
137may contain a reference to an array or hash containing multiple values.)
5f05dabc 138Because of the automatic conversion of scalars, operations, and functions
4633a7c4
LW
139that return scalars don't need to care (and, in fact, can't care) whether
140the context is looking for a string or a number.
141
142Scalars aren't necessarily one thing or another. There's no place to
143declare a scalar variable to be of type "string", or of type "number", or
144type "filehandle", or anything else. Perl is a contextually polymorphic
145language whose scalars can be strings, numbers, or references (which
d28ebecd 146includes objects). While strings and numbers are considered pretty
b88cefa9 147much the same thing for nearly all purposes, references are strongly-typed
54310121 148uncastable pointers with builtin reference-counting and destructor
4633a7c4 149invocation.
a0d0e21e
LW
150
151A scalar value is interpreted as TRUE in the Boolean sense if it is not
152the null string or the number 0 (or its string equivalent, "0"). The
54310121 153Boolean context is just a special kind of scalar context.
a0d0e21e
LW
154
155There are actually two varieties of null scalars: defined and
156undefined. Undefined null scalars are returned when there is no real
157value for something, such as when there was an error, or at end of
158file, or when you refer to an uninitialized variable or element of an
159array. An undefined null scalar may become defined the first time you
160use it as if it were defined, but prior to that you can use the
161defined() operator to determine whether the value is defined or not.
162
54310121 163To find out whether a given string is a valid nonzero number, it's usually
4633a7c4
LW
164enough to test it against both numeric 0 and also lexical "0" (although
165this will cause B<-w> noises). That's because strings that aren't
184e9718 166numbers count as 0, just as they do in B<awk>:
4633a7c4
LW
167
168 if ($str == 0 && $str ne "0") {
169 warn "That doesn't look like a number";
54310121 170 }
4633a7c4 171
cb1a09d0
AD
172That's usually preferable because otherwise you won't treat IEEE notations
173like C<NaN> or C<Infinity> properly. At other times you might prefer to
5a964f20
TC
174use the POSIX::strtod function or a regular expression to check whether
175data is numeric. See L<perlre> for details on regular expressions.
cb1a09d0
AD
176
177 warn "has nondigits" if /\D/;
5a964f20
TC
178 warn "not a natural number" unless /^\d+$/; # rejects -3
179 warn "not an integer" unless /^-?\d+$/; # rejects +3
180 warn "not an integer" unless /^[+-]?\d+$/;
181 warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
182 warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
54310121 183 warn "not a C float"
cb1a09d0
AD
184 unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
185
a0d0e21e
LW
186The length of an array is a scalar value. You may find the length of
187array @days by evaluating C<$#days>, as in B<csh>. (Actually, it's not
5f05dabc 188the length of the array, it's the subscript of the last element, because
a0d0e21e
LW
189there is (ordinarily) a 0th element.) Assigning to C<$#days> changes the
190length of the array. Shortening an array by this method destroys
191intervening values. Lengthening an array that was previously shortened
192I<NO LONGER> recovers the values that were in those elements. (It used to
b88cefa9 193in Perl 4, but we had to break this to make sure destructors were
5a964f20 194called when expected.) You can also gain some miniscule measure of efficiency by
4a6725af 195pre-extending an array that is going to get big. (You can also extend
a0d0e21e
LW
196an array by assigning to an element that is off the end of the array.)
197You can truncate an array down to nothing by assigning the null list ()
198to it. The following are equivalent:
199
200 @whatever = ();
3e3baf6d 201 $#whatever = -1;
a0d0e21e
LW
202
203If you evaluate a named array in a scalar context, it returns the length of
204the array. (Note that this is not true of lists, which return the
5a964f20
TC
205last value, like the C comma operator, nor of built-in functions, which return
206whatever they feel like returning.) The following is always true:
a0d0e21e
LW
207
208 scalar(@whatever) == $#whatever - $[ + 1;
209
184e9718 210Version 5 of Perl changed the semantics of C<$[>: files that don't set
211the value of C<$[> no longer need to worry about whether another
212file changed its value. (In other words, use of C<$[> is deprecated.)
5f05dabc 213So in general you can assume that
a0d0e21e
LW
214
215 scalar(@whatever) == $#whatever + 1;
216
d28ebecd 217Some programmers choose to use an explicit conversion so nothing's
4633a7c4
LW
218left to doubt:
219
220 $element_count = scalar(@whatever);
221
5a964f20 222If you evaluate a hash in a scalar context, it returns a value that is
a0d0e21e
LW
223true if and only if the hash contains any key/value pairs. (If there
224are any key/value pairs, the value returned is a string consisting of
225the number of used buckets and the number of allocated buckets, separated
5f05dabc 226by a slash. This is pretty much useful only to find out whether Perl's
a0d0e21e
LW
227(compiled in) hashing algorithm is performing poorly on your data set.
228For example, you stick 10,000 things in a hash, but evaluating %HASH in
229scalar context reveals "1/16", which means only one out of sixteen buckets
230has been touched, and presumably contains all 10,000 of your items. This
231isn't supposed to happen.)
232
5a964f20
TC
233You can preallocate space for a hash by assigning to the keys() function.
234This rounds up the allocated bucked to the next power of two:
235
236 keys(%users) = 1000; # allocate 1024 buckets
237
a0d0e21e
LW
238=head2 Scalar value constructors
239
240Numeric literals are specified in any of the customary floating point or
241integer formats:
242
a0d0e21e
LW
243 12345
244 12345.67
245 .23E-10
246 0xffff # hex
247 0377 # octal
248 4_294_967_296 # underline for legibility
249
55497cff 250String literals are usually delimited by either single or double
251quotes. They work much like shell quotes: double-quoted string
252literals are subject to backslash and variable substitution;
253single-quoted strings are not (except for "C<\'>" and "C<\\>").
254The usual Unix backslash rules apply for making characters such as
255newline, tab, etc., as well as some more exotic forms. See
256L<perlop/Quote and Quotelike Operators> for a list.
a0d0e21e 257
68dc0745 258Octal or hex representations in string literals (e.g. '0xffff') are not
259automatically converted to their integer representation. The hex() and
260oct() functions make these conversions for you. See L<perlfunc/hex> and
261L<perlfunc/oct> for more details.
262
5f05dabc 263You can also embed newlines directly in your strings, i.e., they can end
a0d0e21e
LW
264on a different line than they begin. This is nice, but if you forget
265your trailing quote, the error will not be reported until Perl finds
266another line containing the quote character, which may be much further
267on in the script. Variable substitution inside strings is limited to
268scalar variables, arrays, and array slices. (In other words,
b88cefa9 269names beginning with $ or @, followed by an optional bracketed
a0d0e21e 270expression as a subscript.) The following code segment prints out "The
184e9718 271price is $Z<>100."
a0d0e21e
LW
272
273 $Price = '$100'; # not interpreted
274 print "The price is $Price.\n"; # interpreted
275
b88cefa9 276As in some shells, you can put curly brackets around the name to
748a9306
LW
277delimit it from following alphanumerics. In fact, an identifier
278within such curlies is forced to be a string, as is any single
279identifier within a hash subscript. Our earlier example,
280
281 $days{'Feb'}
282
283can be written as
284
285 $days{Feb}
286
287and the quotes will be assumed automatically. But anything more complicated
288in the subscript will be interpreted as an expression.
289
290Note that a
a0d0e21e 291single-quoted string must be separated from a preceding word by a
5f05dabc 292space, because single quote is a valid (though deprecated) character in
b88cefa9 293a variable name (see L<perlmod/Packages>).
a0d0e21e 294
68dc0745 295Three special literals are __FILE__, __LINE__, and __PACKAGE__, which
296represent the current filename, line number, and package name at that
297point in your program. They may be used only as separate tokens; they
298will not be interpolated into strings. If there is no current package
5a964f20 299(due to an empty C<package;> directive), __PACKAGE__ is the undefined value.
68dc0745 300
301The tokens __END__ and __DATA__ may be used to indicate the logical end
302of the script before the actual end of file. Any following text is
303ignored, but may be read via a DATA filehandle: main::DATA for __END__,
304or PACKNAME::DATA (where PACKNAME is the current package) for __DATA__.
305The two control characters ^D and ^Z are synonyms for __END__ (or
306__DATA__ in a module). See L<SelfLoader> for more description of
a00c1fe5
CS
307__DATA__, and an example of its use. Note that you cannot read from the
308DATA filehandle in a BEGIN block: the BEGIN block is executed as soon as
309it is seen (during compilation), at which point the corresponding
310__DATA__ (or __END__) token has not yet been seen.
a0d0e21e 311
748a9306 312A word that has no other interpretation in the grammar will
a0d0e21e
LW
313be treated as if it were a quoted string. These are known as
314"barewords". As with filehandles and labels, a bareword that consists
315entirely of lowercase letters risks conflict with future reserved
316words, and if you use the B<-w> switch, Perl will warn you about any
317such words. Some people may wish to outlaw barewords entirely. If you
318say
319
320 use strict 'subs';
321
322then any bareword that would NOT be interpreted as a subroutine call
323produces a compile-time error instead. The restriction lasts to the
54310121 324end of the enclosing block. An inner block may countermand this
a0d0e21e
LW
325by saying C<no strict 'subs'>.
326
327Array variables are interpolated into double-quoted strings by joining all
328the elements of the array with the delimiter specified in the C<$">
184e9718 329variable (C<$LIST_SEPARATOR> in English), space by default. The following
4633a7c4 330are equivalent:
a0d0e21e
LW
331
332 $temp = join($",@ARGV);
333 system "echo $temp";
334
335 system "echo @ARGV";
336
337Within search patterns (which also undergo double-quotish substitution)
338there is a bad ambiguity: Is C</$foo[bar]/> to be interpreted as
339C</${foo}[bar]/> (where C<[bar]> is a character class for the regular
340expression) or as C</${foo[bar]}/> (where C<[bar]> is the subscript to array
341@foo)? If @foo doesn't otherwise exist, then it's obviously a
342character class. If @foo exists, Perl takes a good guess about C<[bar]>,
343and is almost always right. If it does guess wrong, or if you're just
344plain paranoid, you can force the correct interpretation with curly
345brackets as above.
346
55497cff 347A line-oriented form of quoting is based on the shell "here-doc"
348syntax. Following a C<E<lt>E<lt>> you specify a string to terminate
349the quoted material, and all lines following the current line down to
350the terminating string are the value of the item. The terminating
351string may be either an identifier (a word), or some quoted text. If
352quoted, the type of quotes you use determines the treatment of the
353text, just as in regular quoting. An unquoted identifier works like
354double quotes. There must be no space between the C<E<lt>E<lt>> and
355the identifier. (If you put a space it will be treated as a null
3fe9a6f1 356identifier, which is valid, and matches the first empty line.) The
55497cff 357terminating string must appear by itself (unquoted and with no
358surrounding whitespace) on the terminating line.
a0d0e21e 359
54310121 360 print <<EOF;
a0d0e21e
LW
361 The price is $Price.
362 EOF
363
364 print <<"EOF"; # same as above
365 The price is $Price.
366 EOF
367
a0d0e21e
LW
368 print <<`EOC`; # execute commands
369 echo hi there
370 echo lo there
371 EOC
372
373 print <<"foo", <<"bar"; # you can stack them
374 I said foo.
375 foo
376 I said bar.
377 bar
378
d28ebecd 379 myfunc(<<"THIS", 23, <<'THAT');
a0d0e21e
LW
380 Here's a line
381 or two.
382 THIS
54310121 383 and here's another.
a0d0e21e
LW
384 THAT
385
54310121 386Just don't forget that you have to put a semicolon on the end
387to finish the statement, as Perl doesn't know you're not going to
a0d0e21e
LW
388try to do this:
389
390 print <<ABC
391 179231
392 ABC
393 + 20;
394
395
396=head2 List value constructors
397
398List values are denoted by separating individual values by commas
399(and enclosing the list in parentheses where precedence requires it):
400
401 (LIST)
402
748a9306 403In a context not requiring a list value, the value of the list
a0d0e21e
LW
404literal is the value of the final element, as with the C comma operator.
405For example,
406
407 @foo = ('cc', '-E', $bar);
408
409assigns the entire list value to array foo, but
410
411 $foo = ('cc', '-E', $bar);
412
413assigns the value of variable bar to variable foo. Note that the value
414of an actual array in a scalar context is the length of the array; the
54310121 415following assigns the value 3 to $foo:
a0d0e21e
LW
416
417 @foo = ('cc', '-E', $bar);
418 $foo = @foo; # $foo gets 3
419
54310121 420You may have an optional comma before the closing parenthesis of a
a0d0e21e
LW
421list literal, so that you can say:
422
423 @foo = (
424 1,
425 2,
426 3,
427 );
428
429LISTs do automatic interpolation of sublists. That is, when a LIST is
430evaluated, each element of the list is evaluated in a list context, and
431the resulting list value is interpolated into LIST just as if each
5a964f20 432individual element were a member of LIST. Thus arrays and hashes lose their
a0d0e21e
LW
433identity in a LIST--the list
434
5a964f20 435 (@foo,@bar,&SomeSub,%glarch)
a0d0e21e
LW
436
437contains all the elements of @foo followed by all the elements of @bar,
5a964f20
TC
438followed by all the elements returned by the subroutine named SomeSub
439called in a list context, followed by the key/value pairs of %glarch.
a0d0e21e
LW
440To make a list reference that does I<NOT> interpolate, see L<perlref>.
441
442The null list is represented by (). Interpolating it in a list
443has no effect. Thus ((),(),()) is equivalent to (). Similarly,
444interpolating an array with no elements is the same as if no
445array had been interpolated at that point.
446
447A list value may also be subscripted like a normal array. You must
54310121 448put the list in parentheses to avoid ambiguity. For example:
a0d0e21e
LW
449
450 # Stat returns list value.
451 $time = (stat($file))[8];
452
4633a7c4 453 # SYNTAX ERROR HERE.
5f05dabc 454 $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES
4633a7c4 455
a0d0e21e
LW
456 # Find a hex digit.
457 $hexdigit = ('a','b','c','d','e','f')[$digit-10];
458
459 # A "reverse comma operator".
460 return (pop(@foo),pop(@foo))[0];
461
68dc0745 462You may assign to C<undef> in a list. This is useful for throwing
463away some of the return values of a function:
464
465 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
466
a0d0e21e
LW
467Lists may be assigned to if and only if each element of the list
468is legal to assign to:
469
470 ($a, $b, $c) = (1, 2, 3);
471
472 ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
473
4633a7c4
LW
474Array assignment in a scalar context returns the number of elements
475produced by the expression on the right side of the assignment:
476
477 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
478 $x = (($foo,$bar) = f()); # set $x to f()'s return count
479
480This is very handy when you want to do a list assignment in a Boolean
5f05dabc 481context, because most list functions return a null list when finished,
4633a7c4
LW
482which when assigned produces a 0, which is interpreted as FALSE.
483
a0d0e21e
LW
484The final element may be an array or a hash:
485
486 ($a, $b, @rest) = split;
5a964f20 487 my($a, $b, %rest) = @_;
a0d0e21e 488
4633a7c4 489You can actually put an array or hash anywhere in the list, but the first one
a0d0e21e
LW
490in the list will soak up all the values, and anything after it will get
491a null value. This may be useful in a local() or my().
492
493A hash literal contains pairs of values to be interpreted
494as a key and a value:
495
496 # same as map assignment above
497 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
498
4633a7c4
LW
499While literal lists and named arrays are usually interchangeable, that's
500not the case for hashes. Just because you can subscript a list value like
501a normal array does not mean that you can subscript a list value as a
502hash. Likewise, hashes included as parts of other lists (including
503parameters lists and return lists from functions) always flatten out into
504key/value pairs. That's why it's good to use references sometimes.
a0d0e21e 505
4633a7c4
LW
506It is often more readable to use the C<=E<gt>> operator between key/value
507pairs. The C<=E<gt>> operator is mostly just a more visually distinctive
b88cefa9 508synonym for a comma, but it also arranges for its left-hand operand to be
5a964f20 509interpreted as a string--if it's a bareword that would be a legal identifier.
b88cefa9 510This makes it nice for initializing hashes:
a0d0e21e 511
4633a7c4
LW
512 %map = (
513 red => 0x00f,
514 blue => 0x0f0,
515 green => 0xf00,
516 );
517
518or for initializing hash references to be used as records:
519
520 $rec = {
521 witch => 'Mable the Merciless',
522 cat => 'Fluffy the Ferocious',
523 date => '10/31/1776',
524 };
525
526or for using call-by-named-parameter to complicated functions:
527
54310121 528 $field = $query->radio_group(
4633a7c4
LW
529 name => 'group_name',
530 values => ['eenie','meenie','minie'],
531 default => 'meenie',
532 linebreak => 'true',
533 labels => \%labels
534 );
cb1a09d0
AD
535
536Note that just because a hash is initialized in that order doesn't
537mean that it comes out in that order. See L<perlfunc/sort> for examples
538of how to arrange for an output ordering.
539
5f05dabc 540=head2 Typeglobs and Filehandles
cb1a09d0
AD
541
542Perl uses an internal type called a I<typeglob> to hold an entire
543symbol table entry. The type prefix of a typeglob is a C<*>, because
54310121 544it represents all types. This used to be the preferred way to
cb1a09d0 545pass arrays and hashes by reference into a function, but now that
5a964f20
TC
546we have real references, this is seldom needed.
547
548The main use of typeglobs in modern Perl is create symbol table aliases.
549This assignment:
550
551 *this = *that;
552
553makes $this an alias for $that, @this an alias for @that, %this an alias
554for %that, &this an alias for &that, etc. Much safer is to use a reference.
555This:
5f05dabc 556
5a964f20
TC
557 local *Here::blue = \$There::green;
558
559temporarily makes $Here::blue an alias for $There::green, but doesn't
560make @Here::blue an alias for @There::green, or %Here::blue an alias for
561%There::green, etc. See L<perlmod/"Symbol Tables"> for more examples
562of this. Strange though this may seem, this is the basis for the whole
563module import/export system.
564
565Another use for typeglobs is to to pass filehandles into a function or
566to create new filehandles. If you need to use a typeglob to save away
567a filehandle, do it this way:
5f05dabc 568
569 $fh = *STDOUT;
570
571or perhaps as a real reference, like this:
572
573 $fh = \*STDOUT;
574
5a964f20
TC
575See L<perlsub> for examples of using these as indirect filehandles
576in functions.
577
578Typeglobs are also a way to create a local filehandle using the local()
579operator. These last until their block is exited, but may be passed back.
580For example:
5f05dabc 581
582 sub newopen {
583 my $path = shift;
584 local *FH; # not my!
5a964f20 585 open (FH, $path) or return undef;
e05a3a1e 586 return *FH;
5f05dabc 587 }
588 $fh = newopen('/etc/passwd');
589
5a964f20
TC
590Now that we have the *foo{THING} notation, typeglobs aren't used as much
591for filehandle manipulations, although they're still needed to pass brand
592new file and directory handles into or out of functions. That's because
593*HANDLE{IO} only works if HANDLE has already been used as a handle.
594In other words, *FH can be used to create new symbol table entries,
595but *foo{THING} cannot.
596
597Another way to create anonymous filehandles is with the IO::Handle
598module and its ilk. These modules have the advantage of not hiding
599different types of the same name during the local(). See the bottom of
600L<perlfunc/open()> for an example.
cb1a09d0 601
55497cff 602See L<perlref>, L<perlsub>, and L<perlmod/"Symbol Tables"> for more
5a964f20 603discussion on typeglobs and the *foo{THING} syntax.