This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perl 5.000
[perl5.git] / pod / perldata.pod
CommitLineData
a0d0e21e
LW
1=head1 NAME
2
3perldata - Perl data structures
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
43means that $foo[1] is a part of @foo, not a part of $foo. This may
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
63one character, e.g. "$%" or "$$". (Most of these one character names
64have a predefined significance to Perl. For instance, $$ is the
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
111Scalar variables may contain various kinds of singular data, such as
112numbers, strings and references. In general, conversion from one form
113to another is transparent. (A scalar may not contain multiple values,
114but may contain a reference to an array or hash containing multiple
115values.) Because of the automatic conversion of scalars, operations and
116functions that return scalars don't need to care (and, in fact, can't
117care) whether the context is looking for a string or a number.
118
119A scalar value is interpreted as TRUE in the Boolean sense if it is not
120the null string or the number 0 (or its string equivalent, "0"). The
121Boolean context is just a special kind of scalar context.
122
123There are actually two varieties of null scalars: defined and
124undefined. Undefined null scalars are returned when there is no real
125value for something, such as when there was an error, or at end of
126file, or when you refer to an uninitialized variable or element of an
127array. An undefined null scalar may become defined the first time you
128use it as if it were defined, but prior to that you can use the
129defined() operator to determine whether the value is defined or not.
130
131The length of an array is a scalar value. You may find the length of
132array @days by evaluating C<$#days>, as in B<csh>. (Actually, it's not
133the length of the array, it's the subscript of the last element, since
134there is (ordinarily) a 0th element.) Assigning to C<$#days> changes the
135length of the array. Shortening an array by this method destroys
136intervening values. Lengthening an array that was previously shortened
137I<NO LONGER> recovers the values that were in those elements. (It used to
138in Perl 4, but we had to break this make to make sure destructors were
139called when expected.) You can also gain some measure of efficiency by
140preextending an array that is going to get big. (You can also extend
141an array by assigning to an element that is off the end of the array.)
142You can truncate an array down to nothing by assigning the null list ()
143to it. The following are equivalent:
144
145 @whatever = ();
146 $#whatever = $[ - 1;
147
148If you evaluate a named array in a scalar context, it returns the length of
149the array. (Note that this is not true of lists, which return the
150last value, like the C comma operator.) The following is always true:
151
152 scalar(@whatever) == $#whatever - $[ + 1;
153
154Version 5 of Perl changed the semantics of $[: files that don't set
155the value of $[ no longer need to worry about whether another
156file changed its value. (In other words, use of $[ is deprecated.)
157So in general you can just assume that
158
159 scalar(@whatever) == $#whatever + 1;
160
161If you evaluate a hash in a scalar context, it returns a value which is
162true if and only if the hash contains any key/value pairs. (If there
163are any key/value pairs, the value returned is a string consisting of
164the number of used buckets and the number of allocated buckets, separated
165by a slash. This is pretty much only useful to find out whether Perl's
166(compiled in) hashing algorithm is performing poorly on your data set.
167For example, you stick 10,000 things in a hash, but evaluating %HASH in
168scalar context reveals "1/16", which means only one out of sixteen buckets
169has been touched, and presumably contains all 10,000 of your items. This
170isn't supposed to happen.)
171
172=head2 Scalar value constructors
173
174Numeric literals are specified in any of the customary floating point or
175integer formats:
176
177
178 12345
179 12345.67
180 .23E-10
181 0xffff # hex
182 0377 # octal
183 4_294_967_296 # underline for legibility
184
185String literals are delimited by either single or double quotes. They
186work much like shell quotes: double-quoted string literals are subject
187to backslash and variable substitution; single-quoted strings are not
188(except for "C<\'>" and "C<\\>"). The usual Unix backslash rules apply for making
189characters such as newline, tab, etc., as well as some more exotic
190forms. See L<perlop/qq> for a list.
191
192You can also embed newlines directly in your strings, i.e. they can end
193on a different line than they begin. This is nice, but if you forget
194your trailing quote, the error will not be reported until Perl finds
195another line containing the quote character, which may be much further
196on in the script. Variable substitution inside strings is limited to
197scalar variables, arrays, and array slices. (In other words,
198identifiers beginning with $ or @, followed by an optional bracketed
199expression as a subscript.) The following code segment prints out "The
200price is $100."
201
202 $Price = '$100'; # not interpreted
203 print "The price is $Price.\n"; # interpreted
204
205As in some shells, you can put curly brackets around the identifier to
206delimit it from following alphanumerics. Also note that a
207single-quoted string must be separated from a preceding word by a
208space, since single quote is a valid (though discouraged) character in
209an identifier (see L<perlmod/Packages>).
210
211Two special literals are __LINE__ and __FILE__, which represent the
212current line number and filename at that point in your program. They
213may only be used as separate tokens; they will not be interpolated into
214strings. In addition, the token __END__ may be used to indicate the
215logical end of the script before the actual end of file. Any following
216text is ignored, but may be read via the DATA filehandle. (The DATA
217filehandle may read data only from the main script, but not from any
218required file or evaluated string.) The two control characters ^D and
219^Z are synonyms for __END__.
220
221A word that doesn't have any other interpretation in the grammar will
222be treated as if it were a quoted string. These are known as
223"barewords". As with filehandles and labels, a bareword that consists
224entirely of lowercase letters risks conflict with future reserved
225words, and if you use the B<-w> switch, Perl will warn you about any
226such words. Some people may wish to outlaw barewords entirely. If you
227say
228
229 use strict 'subs';
230
231then any bareword that would NOT be interpreted as a subroutine call
232produces a compile-time error instead. The restriction lasts to the
233end of the enclosing block. An inner block may countermand this
234by saying C<no strict 'subs'>.
235
236Array variables are interpolated into double-quoted strings by joining all
237the elements of the array with the delimiter specified in the C<$">
238variable, space by default. The following are equivalent:
239
240 $temp = join($",@ARGV);
241 system "echo $temp";
242
243 system "echo @ARGV";
244
245Within search patterns (which also undergo double-quotish substitution)
246there is a bad ambiguity: Is C</$foo[bar]/> to be interpreted as
247C</${foo}[bar]/> (where C<[bar]> is a character class for the regular
248expression) or as C</${foo[bar]}/> (where C<[bar]> is the subscript to array
249@foo)? If @foo doesn't otherwise exist, then it's obviously a
250character class. If @foo exists, Perl takes a good guess about C<[bar]>,
251and is almost always right. If it does guess wrong, or if you're just
252plain paranoid, you can force the correct interpretation with curly
253brackets as above.
254
255A line-oriented form of quoting is based on the shell "here-doc" syntax.
256Following a C<E<lt>E<lt>> you specify a string to terminate the quoted material,
257and all lines following the current line down to the terminating string
258are the value of the item. The terminating string may be either an
259identifier (a word), or some quoted text. If quoted, the type of
260quotes you use determines the treatment of the text, just as in regular
261quoting. An unquoted identifier works like double quotes. There must
262be no space between the C<E<lt>E<lt>> and the identifier. (If you put a space it
263will be treated as a null identifier, which is valid, and matches the
264first blank line--see the Merry Christmas example below.) The terminating
265string must appear by itself (unquoted and with no surrounding
266whitespace) on the terminating line.
267
268 print <<EOF; # same as above
269 The price is $Price.
270 EOF
271
272 print <<"EOF"; # same as above
273 The price is $Price.
274 EOF
275
276 print << x 10; # Legal but discouraged. Use <<"".
277 Merry Christmas!
278
279 print <<`EOC`; # execute commands
280 echo hi there
281 echo lo there
282 EOC
283
284 print <<"foo", <<"bar"; # you can stack them
285 I said foo.
286 foo
287 I said bar.
288 bar
289
290 myfunc(<<"THIS", 23, <<'THAT'');
291 Here's a line
292 or two.
293 THIS
294 and here another.
295 THAT
296
297Just don't forget that you have to put a semicolon on the end
298to finish the statement, as Perl doesn't know you're not going to
299try to do this:
300
301 print <<ABC
302 179231
303 ABC
304 + 20;
305
306
307=head2 List value constructors
308
309List values are denoted by separating individual values by commas
310(and enclosing the list in parentheses where precedence requires it):
311
312 (LIST)
313
314In a context not requiring an list value, the value of the list
315literal is the value of the final element, as with the C comma operator.
316For example,
317
318 @foo = ('cc', '-E', $bar);
319
320assigns the entire list value to array foo, but
321
322 $foo = ('cc', '-E', $bar);
323
324assigns the value of variable bar to variable foo. Note that the value
325of an actual array in a scalar context is the length of the array; the
326following assigns to $foo the value 3:
327
328 @foo = ('cc', '-E', $bar);
329 $foo = @foo; # $foo gets 3
330
331You may have an optional comma before the closing parenthesis of an
332list literal, so that you can say:
333
334 @foo = (
335 1,
336 2,
337 3,
338 );
339
340LISTs do automatic interpolation of sublists. That is, when a LIST is
341evaluated, each element of the list is evaluated in a list context, and
342the resulting list value is interpolated into LIST just as if each
343individual element were a member of LIST. Thus arrays lose their
344identity in a LIST--the list
345
346 (@foo,@bar,&SomeSub)
347
348contains all the elements of @foo followed by all the elements of @bar,
349followed by all the elements returned by the subroutine named SomeSub.
350To make a list reference that does I<NOT> interpolate, see L<perlref>.
351
352The null list is represented by (). Interpolating it in a list
353has no effect. Thus ((),(),()) is equivalent to (). Similarly,
354interpolating an array with no elements is the same as if no
355array had been interpolated at that point.
356
357A list value may also be subscripted like a normal array. You must
358put the list in parentheses to avoid ambiguity. Examples:
359
360 # Stat returns list value.
361 $time = (stat($file))[8];
362
363 # Find a hex digit.
364 $hexdigit = ('a','b','c','d','e','f')[$digit-10];
365
366 # A "reverse comma operator".
367 return (pop(@foo),pop(@foo))[0];
368
369Lists may be assigned to if and only if each element of the list
370is legal to assign to:
371
372 ($a, $b, $c) = (1, 2, 3);
373
374 ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
375
376The final element may be an array or a hash:
377
378 ($a, $b, @rest) = split;
379 local($a, $b, %rest) = @_;
380
381You can actually put an array anywhere in the list, but the first array
382in the list will soak up all the values, and anything after it will get
383a null value. This may be useful in a local() or my().
384
385A hash literal contains pairs of values to be interpreted
386as a key and a value:
387
388 # same as map assignment above
389 %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
390
391It is often more readable to use the C<=E<gt>> operator between key/value pairs
392(the C<=E<gt>> operator is actually nothing more than a more visually
393distinctive synonym for a comma):
394
395 %map = (
396 'red' => 0x00f,
397 'blue' => 0x0f0,
398 'green' => 0xf00,
399 );
400
401Array assignment in a scalar context returns the number of elements
402produced by the expression on the right side of the assignment:
403
404 $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
405
406This is very handy when you want to do a list assignment in a Boolean
407context, since most list functions return a null list when finished,
408which when assigned produces a 0, which is interpreted as FALSE.