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