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