This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
pod/perlipc.pod patch
[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
PP
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
22packages, in order to locate the namespace in which to look
23up the final identifier (see L<perlmod/Packages> for details).
184e9718 24It's possible to substitute for a simple identifier an expression
b88cefa9
PP
25which produces a reference to the value at runtime; this is
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
30normal variables. Strings which match parenthesized parts of a
31regular expression are saved under names containing only digits after
32the C<$> (see L<perlop> and L<perlre>). In addition, several special
33variables which provide windows into the inner working of Perl have names
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
68Since variable and array references always start with '$', '@', or '%',
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
75with future reserved words.) Case I<IS> significant--"FOO", "Foo" and
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
83Names that start with a digit may only contain more digits. Names
84which do not start with a letter, underscore, or digit are limited to
cb1a09d0
AD
85one character, e.g. C<$%> or C<$$>. (Most of these one character names
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.)
138Because of the automatic conversion of scalars, operations and functions
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
4633a7c4
LW
148uncastable pointers with built-in reference-counting and destructor
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
4633a7c4 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
cb1a09d0 163To find out whether a given string is a valid non-zero 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";
170 }
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
174use a regular expression to check whether data is numeric. See L<perlre>
175for 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
a0d0e21e
LW
184The length of an array is a scalar value. You may find the length of
185array @days by evaluating C<$#days>, as in B<csh>. (Actually, it's not
186the length of the array, it's the subscript of the last element, since
187there is (ordinarily) a 0th element.) Assigning to C<$#days> changes the
188length of the array. Shortening an array by this method destroys
189intervening values. Lengthening an array that was previously shortened
190I<NO LONGER> recovers the values that were in those elements. (It used to
b88cefa9 191in Perl 4, but we had to break this to make sure destructors were
a0d0e21e
LW
192called when expected.) You can also gain some measure of efficiency by
193preextending an array that is going to get big. (You can also extend
194an array by assigning to an element that is off the end of the array.)
195You can truncate an array down to nothing by assigning the null list ()
196to it. The following are equivalent:
197
198 @whatever = ();
199 $#whatever = $[ - 1;
200
201If you evaluate a named array in a scalar context, it returns the length of
202the array. (Note that this is not true of lists, which return the
203last value, like the C comma operator.) The following is always true:
204
205 scalar(@whatever) == $#whatever - $[ + 1;
206
184e9718
PP
207Version 5 of Perl changed the semantics of C<$[>: files that don't set
208the value of C<$[> no longer need to worry about whether another
209file changed its value. (In other words, use of C<$[> is deprecated.)
a0d0e21e
LW
210So in general you can just assume that
211
212 scalar(@whatever) == $#whatever + 1;
213
d28ebecd 214Some programmers choose to use an explicit conversion so nothing's
4633a7c4
LW
215left to doubt:
216
217 $element_count = scalar(@whatever);
218
a0d0e21e
LW
219If you evaluate a hash in a scalar context, it returns a value which is
220true if and only if the hash contains any key/value pairs. (If there
221are any key/value pairs, the value returned is a string consisting of
222the number of used buckets and the number of allocated buckets, separated
223by a slash. This is pretty much only useful to find out whether Perl's
224(compiled in) hashing algorithm is performing poorly on your data set.
225For example, you stick 10,000 things in a hash, but evaluating %HASH in
226scalar context reveals "1/16", which means only one out of sixteen buckets
227has been touched, and presumably contains all 10,000 of your items. This
228isn't supposed to happen.)
229
230=head2 Scalar value constructors
231
232Numeric literals are specified in any of the customary floating point or
233integer formats:
234
a0d0e21e
LW
235 12345
236 12345.67
237 .23E-10
238 0xffff # hex
239 0377 # octal
240 4_294_967_296 # underline for legibility
241
55497cff
PP
242String literals are usually delimited by either single or double
243quotes. They work much like shell quotes: double-quoted string
244literals are subject to backslash and variable substitution;
245single-quoted strings are not (except for "C<\'>" and "C<\\>").
246The usual Unix backslash rules apply for making characters such as
247newline, tab, etc., as well as some more exotic forms. See
248L<perlop/Quote and Quotelike Operators> for a list.
a0d0e21e
LW
249
250You can also embed newlines directly in your strings, i.e. they can end
251on a different line than they begin. This is nice, but if you forget
252your trailing quote, the error will not be reported until Perl finds
253another line containing the quote character, which may be much further
254on in the script. Variable substitution inside strings is limited to
255scalar variables, arrays, and array slices. (In other words,
b88cefa9 256names beginning with $ or @, followed by an optional bracketed
a0d0e21e 257expression as a subscript.) The following code segment prints out "The
184e9718 258price is $Z<>100."
a0d0e21e
LW
259
260 $Price = '$100'; # not interpreted
261 print "The price is $Price.\n"; # interpreted
262
b88cefa9 263As in some shells, you can put curly brackets around the name to
748a9306
LW
264delimit it from following alphanumerics. In fact, an identifier
265within such curlies is forced to be a string, as is any single
266identifier within a hash subscript. Our earlier example,
267
268 $days{'Feb'}
269
270can be written as
271
272 $days{Feb}
273
274and the quotes will be assumed automatically. But anything more complicated
275in the subscript will be interpreted as an expression.
276
277Note that a
a0d0e21e 278single-quoted string must be separated from a preceding word by a
748a9306 279space, since single quote is a valid (though deprecated) character in
b88cefa9 280a variable name (see L<perlmod/Packages>).
a0d0e21e
LW
281
282Two special literals are __LINE__ and __FILE__, which represent the
283current line number and filename at that point in your program. They
284may only be used as separate tokens; they will not be interpolated into
285strings. In addition, the token __END__ may be used to indicate the
286logical end of the script before the actual end of file. Any following
287text is ignored, but may be read via the DATA filehandle. (The DATA
288filehandle may read data only from the main script, but not from any
289required file or evaluated string.) The two control characters ^D and
cb1a09d0
AD
290^Z are synonyms for __END__ (or __DATA__ in a module; see L<SelfLoader> for
291details on __DATA__).
a0d0e21e 292
748a9306 293A word that has no other interpretation in the grammar will
a0d0e21e
LW
294be treated as if it were a quoted string. These are known as
295"barewords". As with filehandles and labels, a bareword that consists
296entirely of lowercase letters risks conflict with future reserved
297words, and if you use the B<-w> switch, Perl will warn you about any
298such words. Some people may wish to outlaw barewords entirely. If you
299say
300
301 use strict 'subs';
302
303then any bareword that would NOT be interpreted as a subroutine call
304produces a compile-time error instead. The restriction lasts to the
305end of the enclosing block. An inner block may countermand this
306by saying C<no strict 'subs'>.
307
308Array variables are interpolated into double-quoted strings by joining all
309the elements of the array with the delimiter specified in the C<$">
184e9718 310variable (C<$LIST_SEPARATOR> in English), space by default. The following
4633a7c4 311are equivalent:
a0d0e21e
LW
312
313 $temp = join($",@ARGV);
314 system "echo $temp";
315
316 system "echo @ARGV";
317
318Within search patterns (which also undergo double-quotish substitution)
319there is a bad ambiguity: Is C</$foo[bar]/> to be interpreted as
320C</${foo}[bar]/> (where C<[bar]> is a character class for the regular
321expression) or as C</${foo[bar]}/> (where C<[bar]> is the subscript to array
322@foo)? If @foo doesn't otherwise exist, then it's obviously a
323character class. If @foo exists, Perl takes a good guess about C<[bar]>,
324and is almost always right. If it does guess wrong, or if you're just
325plain paranoid, you can force the correct interpretation with curly
326brackets as above.
327
55497cff
PP
328A line-oriented form of quoting is based on the shell "here-doc"
329syntax. Following a C<E<lt>E<lt>> you specify a string to terminate
330the quoted material, and all lines following the current line down to
331the terminating string are the value of the item. The terminating
332string may be either an identifier (a word), or some quoted text. If
333quoted, the type of quotes you use determines the treatment of the
334text, just as in regular quoting. An unquoted identifier works like
335double quotes. There must be no space between the C<E<lt>E<lt>> and
336the identifier. (If you put a space it will be treated as a null
337identifier, which is valid, and matches the first blank line.) The
338terminating string must appear by itself (unquoted and with no
339surrounding whitespace) on the terminating line.
a0d0e21e 340
c07a80fd 341 print <<EOF;
a0d0e21e
LW
342 The price is $Price.
343 EOF
344
345 print <<"EOF"; # same as above
346 The price is $Price.
347 EOF
348
a0d0e21e
LW
349 print <<`EOC`; # execute commands
350 echo hi there
351 echo lo there
352 EOC
353
354 print <<"foo", <<"bar"; # you can stack them
355 I said foo.
356 foo
357 I said bar.
358 bar
359
d28ebecd 360 myfunc(<<"THIS", 23, <<'THAT');
a0d0e21e
LW
361 Here's a line
362 or two.
363 THIS
364 and here another.
365 THAT
366
367Just don't forget that you have to put a semicolon on the end
368to finish the statement, as Perl doesn't know you're not going to
369try to do this:
370
371 print <<ABC
372 179231
373 ABC
374 + 20;
375
376
377=head2 List value constructors
378
379List values are denoted by separating individual values by commas
380(and enclosing the list in parentheses where precedence requires it):
381
382 (LIST)
383
748a9306 384In a context not requiring a list value, the value of the list
a0d0e21e
LW
385literal is the value of the final element, as with the C comma operator.
386For example,
387
388 @foo = ('cc', '-E', $bar);
389
390assigns the entire list value to array foo, but
391
392 $foo = ('cc', '-E', $bar);
393
394assigns the value of variable bar to variable foo. Note that the value
395of an actual array in a scalar context is the length of the array; the
396following assigns to $foo the value 3:
397
398 @foo = ('cc', '-E', $bar);
399 $foo = @foo; # $foo gets 3
400
401You may have an optional comma before the closing parenthesis of an
402list literal, so that you can say:
403
404 @foo = (
405 1,
406 2,
407 3,
408 );
409
410LISTs do automatic interpolation of sublists. That is, when a LIST is
411evaluated, each element of the list is evaluated in a list context, and
412the resulting list value is interpolated into LIST just as if each
413individual element were a member of LIST. Thus arrays lose their
414identity in a LIST--the list
415
416 (@foo,@bar,&SomeSub)
417
418contains all the elements of @foo followed by all the elements of @bar,
4633a7c4
LW
419followed by all the elements returned by the subroutine named SomeSub when
420it's called in a list context.
a0d0e21e
LW
421To make a list reference that does I<NOT> interpolate, see L<perlref>.
422
423The null list is represented by (). Interpolating it in a list
424has no effect. Thus ((),(),()) is equivalent to (). Similarly,
425interpolating an array with no elements is the same as if no
426array had been interpolated at that point.
427
428A list value may also be subscripted like a normal array. You must
429put the list in parentheses to avoid ambiguity. Examples:
430
431 # Stat returns list value.
432 $time = (stat($file))[8];
433
4633a7c4
LW
434 # SYNTAX ERROR HERE.
435 $time = stat($file)[8]; # OOPS, FORGOT PARENS
436
a0d0e21e
LW
437 # Find a hex digit.
438 $hexdigit = ('a','b','c','d','e','f')[$digit-10];
439
440 # A "reverse comma operator".
441 return (pop(@foo),pop(@foo))[0];
442
443Lists may be assigned to if and only if each element of the list
444is legal to assign to:
445
446 ($a, $b, $c) = (1, 2, 3);
447
448 ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
449
4633a7c4
LW
450Array assignment in a scalar context returns the number of elements
451produced by the expression on the right side of the assignment:
452
453 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
454 $x = (($foo,$bar) = f()); # set $x to f()'s return count
455
456This is very handy when you want to do a list assignment in a Boolean
457context, since most list functions return a null list when finished,
458which when assigned produces a 0, which is interpreted as FALSE.
459
a0d0e21e
LW
460The final element may be an array or a hash:
461
462 ($a, $b, @rest) = split;
463 local($a, $b, %rest) = @_;
464
4633a7c4 465You can actually put an array or hash anywhere in the list, but the first one
a0d0e21e
LW
466in the list will soak up all the values, and anything after it will get
467a null value. This may be useful in a local() or my().
468
469A hash literal contains pairs of values to be interpreted
470as a key and a value:
471
472 # same as map assignment above
473 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
474
4633a7c4
LW
475While literal lists and named arrays are usually interchangeable, that's
476not the case for hashes. Just because you can subscript a list value like
477a normal array does not mean that you can subscript a list value as a
478hash. Likewise, hashes included as parts of other lists (including
479parameters lists and return lists from functions) always flatten out into
480key/value pairs. That's why it's good to use references sometimes.
a0d0e21e 481
4633a7c4
LW
482It is often more readable to use the C<=E<gt>> operator between key/value
483pairs. The C<=E<gt>> operator is mostly just a more visually distinctive
b88cefa9
PP
484synonym for a comma, but it also arranges for its left-hand operand to be
485interpreted as a string, if it's a bareword which would be a legal identifier.
486This makes it nice for initializing hashes:
a0d0e21e 487
4633a7c4
LW
488 %map = (
489 red => 0x00f,
490 blue => 0x0f0,
491 green => 0xf00,
492 );
493
494or for initializing hash references to be used as records:
495
496 $rec = {
497 witch => 'Mable the Merciless',
498 cat => 'Fluffy the Ferocious',
499 date => '10/31/1776',
500 };
501
502or for using call-by-named-parameter to complicated functions:
503
504 $field = $query->radio_group(
505 name => 'group_name',
506 values => ['eenie','meenie','minie'],
507 default => 'meenie',
508 linebreak => 'true',
509 labels => \%labels
510 );
cb1a09d0
AD
511
512Note that just because a hash is initialized in that order doesn't
513mean that it comes out in that order. See L<perlfunc/sort> for examples
514of how to arrange for an output ordering.
515
55497cff 516=head2 Typeglobs
cb1a09d0
AD
517
518Perl uses an internal type called a I<typeglob> to hold an entire
519symbol table entry. The type prefix of a typeglob is a C<*>, because
520it represents all types. This used to be the preferred way to
521pass arrays and hashes by reference into a function, but now that
55497cff
PP
522we have real references, this is seldom needed. It also used to be the
523preferred way to pass filehandles into a function, but now
524that we have the *foo{THING} notation it isn't often needed for that,
525either.
cb1a09d0 526
55497cff
PP
527See L<perlref>, L<perlsub>, and L<perlmod/"Symbol Tables"> for more
528discussion on typeglobs.