Commit | Line | Data |
---|---|---|
a0d0e21e LW |
1 | =head1 NAME |
2 | ||
cb1a09d0 | 3 | perldata - Perl data types |
a0d0e21e LW |
4 | |
5 | =head1 DESCRIPTION | |
6 | ||
7 | =head2 Variable names | |
8 | ||
d55a8828 | 9 | Perl has three built-in data types: scalars, arrays of scalars, and |
692ef166 SF |
10 | associative arrays of scalars, known as "hashes". A scalar is a |
11 | single string (of any size, limited only by the available memory), | |
12 | number, or a reference to something (which will be discussed | |
13 | in L<perlref>). Normal arrays are ordered lists of scalars indexed | |
14 | by number, starting with 0. Hashes are unordered collections of scalar | |
15 | values indexed by their associated string key. | |
a0d0e21e | 16 | |
d55a8828 | 17 | Values are usually referred to by name, or through a named reference. |
b88cefa9 | 18 | The first character of the name tells you to what sort of data |
19 | structure it refers. The rest of the name tells you the particular | |
d55a8828 TC |
20 | value to which it refers. Usually this name is a single I<identifier>, |
21 | that is, a string beginning with a letter or underscore, and | |
22 | containing letters, underscores, and digits. In some cases, it may | |
23 | be a chain of identifiers, separated by C<::> (or by the slightly | |
24 | archaic C<'>); all but the last are interpreted as names of packages, | |
25 | to locate the namespace in which to look up the final identifier | |
26 | (see L<perlmod/Packages> for details). It's possible to substitute | |
27 | for a simple identifier, an expression that produces a reference | |
28 | to the value at runtime. This is described in more detail below | |
29 | and in L<perlref>. | |
30 | ||
31 | Perl also has its own built-in variables whose names don't follow | |
32 | these rules. They have strange names so they don't accidentally | |
33 | collide with one of your normal variables. Strings that match | |
34 | parenthesized parts of a regular expression are saved under names | |
35 | containing only digits after the C<$> (see L<perlop> and L<perlre>). | |
36 | In addition, several special variables that provide windows into | |
37 | the inner working of Perl have names containing punctuation characters | |
38 | and control characters. These are documented in L<perlvar>. | |
39 | ||
40 | Scalar values are always named with '$', even when referring to a | |
41 | scalar that is part of an array or a hash. The '$' symbol works | |
42 | semantically like the English word "the" in that it indicates a | |
43 | single value is expected. | |
a0d0e21e LW |
44 | |
45 | $days # the simple scalar value "days" | |
46 | $days[28] # the 29th element of array @days | |
47 | $days{'Feb'} # the 'Feb' value from hash %days | |
48 | $#days # the last index of array @days | |
49 | ||
d55a8828 TC |
50 | Entire arrays (and slices of arrays and hashes) are denoted by '@', |
51 | which works much like the word "these" or "those" does in English, | |
52 | in that it indicates multiple values are expected. | |
a0d0e21e LW |
53 | |
54 | @days # ($days[0], $days[1],... $days[n]) | |
d55a8828 | 55 | @days[3,4,5] # same as ($days[3],$days[4],$days[5]) |
a0d0e21e LW |
56 | @days{'a','c'} # same as ($days{'a'},$days{'c'}) |
57 | ||
d55a8828 | 58 | Entire hashes are denoted by '%': |
a0d0e21e LW |
59 | |
60 | %days # (key1, val1, key2, val2 ...) | |
61 | ||
d55a8828 TC |
62 | In addition, subroutines are named with an initial '&', though this |
63 | is optional when unambiguous, just as the word "do" is often redundant | |
64 | in English. Symbol table entries can be named with an initial '*', | |
65 | but you don't really care about that yet (if ever :-). | |
66 | ||
67 | Every variable type has its own namespace, as do several | |
68 | non-variable identifiers. This means that you can, without fear | |
69 | of conflict, use the same name for a scalar variable, an array, or | |
70 | a hash--or, for that matter, for a filehandle, a directory handle, a | |
71 | subroutine name, a format name, or a label. This means that $foo | |
72 | and @foo are two different variables. It also means that C<$foo[1]> | |
73 | is a part of @foo, not a part of $foo. This may seem a bit weird, | |
74 | but that's okay, because it is weird. | |
75 | ||
76 | Because variable references always start with '$', '@', or '%', the | |
77 | "reserved" words aren't in fact reserved with respect to variable | |
78 | names. They I<are> reserved with respect to labels and filehandles, | |
79 | however, which don't have an initial special character. You can't | |
80 | have a filehandle named "log", for instance. Hint: you could say | |
81 | C<open(LOG,'logfile')> rather than C<open(log,'logfile')>. Using | |
82 | uppercase filehandles also improves readability and protects you | |
83 | from conflict with future reserved words. Case I<is> significant--"FOO", | |
84 | "Foo", and "foo" are all different names. Names that start with a | |
85 | letter or underscore may also contain digits and underscores. | |
a0d0e21e LW |
86 | |
87 | It is possible to replace such an alphanumeric name with an expression | |
d55a8828 | 88 | that returns a reference to the appropriate type. For a description |
a0d0e21e LW |
89 | of this, see L<perlref>. |
90 | ||
5f05dabc | 91 | Names that start with a digit may contain only more digits. Names |
9539f610 RGS |
92 | that do not start with a letter, underscore, digit or a caret (i.e. |
93 | a control character) are limited to one character, e.g., C<$%> or | |
94 | C<$$>. (Most of these one character names have a predefined | |
95 | significance to Perl. For instance, C<$$> is the current process | |
96 | id.) | |
a0d0e21e LW |
97 | |
98 | =head2 Context | |
99 | ||
100 | The interpretation of operations and values in Perl sometimes depends | |
101 | on the requirements of the context around the operation or value. | |
d55a8828 | 102 | There are two major contexts: list and scalar. Certain operations |
a0d0e21e | 103 | return list values in contexts wanting a list, and scalar values |
d55a8828 TC |
104 | otherwise. If this is true of an operation it will be mentioned in |
105 | the documentation for that operation. In other words, Perl overloads | |
a0d0e21e | 106 | certain operations based on whether the expected return value is |
d55a8828 TC |
107 | singular or plural. Some words in English work this way, like "fish" |
108 | and "sheep". | |
a0d0e21e LW |
109 | |
110 | In a reciprocal fashion, an operation provides either a scalar or a | |
111 | list context to each of its arguments. For example, if you say | |
112 | ||
113 | int( <STDIN> ) | |
114 | ||
c47ff5f1 | 115 | the integer operation provides scalar context for the <> |
a0d0e21e LW |
116 | operator, which responds by reading one line from STDIN and passing it |
117 | back to the integer operation, which will then find the integer value | |
118 | of that line and return that. If, on the other hand, you say | |
119 | ||
120 | sort( <STDIN> ) | |
121 | ||
c47ff5f1 | 122 | then the sort operation provides list context for <>, which |
a0d0e21e LW |
123 | will proceed to read every line available up to the end of file, and |
124 | pass that list of lines back to the sort routine, which will then | |
125 | sort those lines and return them as a list to whatever the context | |
126 | of the sort was. | |
127 | ||
d55a8828 TC |
128 | Assignment is a little bit special in that it uses its left argument |
129 | to determine the context for the right argument. Assignment to a | |
130 | scalar evaluates the right-hand side in scalar context, while | |
131 | assignment to an array or hash evaluates the righthand side in list | |
132 | context. Assignment to a list (or slice, which is just a list | |
133 | anyway) also evaluates the righthand side in list context. | |
134 | ||
9f1b1f2d GS |
135 | When you use the C<use warnings> pragma or Perl's B<-w> command-line |
136 | option, you may see warnings | |
d55a8828 TC |
137 | about useless uses of constants or functions in "void context". |
138 | Void context just means the value has been discarded, such as a | |
139 | statement containing only C<"fred";> or C<getpwuid(0);>. It still | |
140 | counts as scalar context for functions that care whether or not | |
141 | they're being called in list context. | |
142 | ||
143 | User-defined subroutines may choose to care whether they are being | |
144 | called in a void, scalar, or list context. Most subroutines do not | |
145 | need to bother, though. That's because both scalars and lists are | |
146 | automatically interpolated into lists. See L<perlfunc/wantarray> | |
147 | for how you would dynamically discern your function's calling | |
148 | context. | |
a0d0e21e LW |
149 | |
150 | =head2 Scalar values | |
151 | ||
d55a8828 TC |
152 | All data in Perl is a scalar, an array of scalars, or a hash of |
153 | scalars. A scalar may contain one single value in any of three | |
154 | different flavors: a number, a string, or a reference. In general, | |
155 | conversion from one form to another is transparent. Although a | |
156 | scalar may not directly hold multiple values, it may contain a | |
157 | reference to an array or hash which in turn contains multiple values. | |
158 | ||
159 | Scalars aren't necessarily one thing or another. There's no place | |
160 | to declare a scalar variable to be of type "string", type "number", | |
161 | type "reference", or anything else. Because of the automatic | |
162 | conversion of scalars, operations that return scalars don't need | |
163 | to care (and in fact, cannot care) whether their caller is looking | |
164 | for a string, a number, or a reference. Perl is a contextually | |
165 | polymorphic language whose scalars can be strings, numbers, or | |
166 | references (which includes objects). Although strings and numbers | |
167 | are considered pretty much the same thing for nearly all purposes, | |
168 | references are strongly-typed, uncastable pointers with builtin | |
169 | reference-counting and destructor invocation. | |
a0d0e21e LW |
170 | |
171 | A scalar value is interpreted as TRUE in the Boolean sense if it is not | |
19799a22 | 172 | the null string or the number 0 (or its string equivalent, "0"). The |
d55a8828 TC |
173 | Boolean context is just a special kind of scalar context where no |
174 | conversion to a string or a number is ever performed. | |
175 | ||
176 | There are actually two varieties of null strings (sometimes referred | |
177 | to as "empty" strings), a defined one and an undefined one. The | |
178 | defined version is just a string of length zero, such as C<"">. | |
179 | The undefined version is the value that indicates that there is | |
180 | no real value for something, such as when there was an error, or | |
181 | at end of file, or when you refer to an uninitialized variable or | |
182 | element of an array or hash. Although in early versions of Perl, | |
183 | an undefined scalar could become defined when first used in a | |
184 | place expecting a defined value, this no longer happens except for | |
185 | rare cases of autovivification as explained in L<perlref>. You can | |
186 | use the defined() operator to determine whether a scalar value is | |
187 | defined (this has no meaning on arrays or hashes), and the undef() | |
188 | operator to produce an undefined value. | |
189 | ||
190 | To find out whether a given string is a valid non-zero number, it's | |
191 | sometimes enough to test it against both numeric 0 and also lexical | |
692ef166 SF |
192 | "0" (although this will cause noises if warnings are on). That's |
193 | because strings that aren't numbers count as 0, just as they do in B<awk>: | |
4633a7c4 LW |
194 | |
195 | if ($str == 0 && $str ne "0") { | |
196 | warn "That doesn't look like a number"; | |
54310121 | 197 | } |
4633a7c4 | 198 | |
d55a8828 TC |
199 | That method may be best because otherwise you won't treat IEEE |
200 | notations like C<NaN> or C<Infinity> properly. At other times, you | |
201 | might prefer to determine whether string data can be used numerically | |
202 | by calling the POSIX::strtod() function or by inspecting your string | |
203 | with a regular expression (as documented in L<perlre>). | |
cb1a09d0 AD |
204 | |
205 | warn "has nondigits" if /\D/; | |
5a964f20 TC |
206 | warn "not a natural number" unless /^\d+$/; # rejects -3 |
207 | warn "not an integer" unless /^-?\d+$/; # rejects +3 | |
208 | warn "not an integer" unless /^[+-]?\d+$/; | |
209 | warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2 | |
210 | warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/; | |
54310121 | 211 | warn "not a C float" |
cb1a09d0 AD |
212 | unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/; |
213 | ||
d55a8828 | 214 | The length of an array is a scalar value. You may find the length |
fc518ee5 JA |
215 | of array @days by evaluating C<$#days>, as in B<csh>. However, this |
216 | isn't the length of the array; it's the subscript of the last element, | |
217 | which is a different value since there is ordinarily a 0th element. | |
d55a8828 TC |
218 | Assigning to C<$#days> actually changes the length of the array. |
219 | Shortening an array this way destroys intervening values. Lengthening | |
220 | an array that was previously shortened does not recover values | |
221 | that were in those elements. (It used to do so in Perl 4, but we | |
222 | had to break this to make sure destructors were called when expected.) | |
223 | ||
210b36aa | 224 | You can also gain some minuscule measure of efficiency by pre-extending |
d55a8828 TC |
225 | an array that is going to get big. You can also extend an array |
226 | by assigning to an element that is off the end of the array. You | |
19799a22 | 227 | can truncate an array down to nothing by assigning the null list |
d55a8828 | 228 | () to it. The following are equivalent: |
a0d0e21e | 229 | |
84f709e7 | 230 | @whatever = (); |
3e3baf6d | 231 | $#whatever = -1; |
a0d0e21e | 232 | |
d55a8828 TC |
233 | If you evaluate an array in scalar context, it returns the length |
234 | of the array. (Note that this is not true of lists, which return | |
235 | the last value, like the C comma operator, nor of built-in functions, | |
236 | which return whatever they feel like returning.) The following is | |
237 | always true: | |
a0d0e21e | 238 | |
84f709e7 JH |
239 | scalar(@whatever) == $#whatever - $[ + 1; |
240 | ||
241 | Version 5 of Perl changed the semantics of C<$[>: files that don't set | |
242 | the value of C<$[> no longer need to worry about whether another | |
243 | file changed its value. (In other words, use of C<$[> is deprecated.) | |
244 | So in general you can assume that | |
245 | ||
a0d0e21e LW |
246 | scalar(@whatever) == $#whatever + 1; |
247 | ||
d55a8828 TC |
248 | Some programmers choose to use an explicit conversion so as to |
249 | leave nothing to doubt: | |
4633a7c4 LW |
250 | |
251 | $element_count = scalar(@whatever); | |
252 | ||
d55a8828 TC |
253 | If you evaluate a hash in scalar context, it returns false if the |
254 | hash is empty. If there are any key/value pairs, it returns true; | |
255 | more precisely, the value returned is a string consisting of the | |
256 | number of used buckets and the number of allocated buckets, separated | |
257 | by a slash. This is pretty much useful only to find out whether | |
258 | Perl's internal hashing algorithm is performing poorly on your data | |
259 | set. For example, you stick 10,000 things in a hash, but evaluating | |
260 | %HASH in scalar context reveals C<"1/16">, which means only one out | |
261 | of sixteen buckets has been touched, and presumably contains all | |
126c71c8 YST |
262 | 10,000 of your items. This isn't supposed to happen. If a tied hash |
263 | is evaluated in scalar context, a fatal error will result, since this | |
264 | bucket usage information is currently not available for tied hashes. | |
a0d0e21e | 265 | |
5a964f20 | 266 | You can preallocate space for a hash by assigning to the keys() function. |
65841adf | 267 | This rounds up the allocated buckets to the next power of two: |
5a964f20 TC |
268 | |
269 | keys(%users) = 1000; # allocate 1024 buckets | |
270 | ||
a0d0e21e LW |
271 | =head2 Scalar value constructors |
272 | ||
d55a8828 | 273 | Numeric literals are specified in any of the following floating point or |
a0d0e21e LW |
274 | integer formats: |
275 | ||
a0d0e21e LW |
276 | 12345 |
277 | 12345.67 | |
d55a8828 | 278 | .23E-10 # a very small number |
928753ea | 279 | 3.14_15_92 # a very important number |
1d277562 | 280 | 4_294_967_296 # underscore for legibility |
d55a8828 | 281 | 0xff # hex |
928753ea | 282 | 0xdead_beef # more hex |
d55a8828 TC |
283 | 0377 # octal |
284 | 0b011011 # binary | |
a0d0e21e | 285 | |
d4ced10d JH |
286 | You are allowed to use underscores (underbars) in numeric literals |
287 | between digits for legibility. You could, for example, group binary | |
288 | digits by threes (as for a Unix-style mode argument such as 0b110_100_100) | |
289 | or by fours (to represent nibbles, as in 0b1010_0110) or in other groups. | |
1d277562 | 290 | |
55497cff | 291 | String literals are usually delimited by either single or double |
d55a8828 TC |
292 | quotes. They work much like quotes in the standard Unix shells: |
293 | double-quoted string literals are subject to backslash and variable | |
19799a22 GS |
294 | substitution; single-quoted strings are not (except for C<\'> and |
295 | C<\\>). The usual C-style backslash rules apply for making | |
d55a8828 | 296 | characters such as newline, tab, etc., as well as some more exotic |
4a4eefd0 | 297 | forms. See L<perlop/"Quote and Quote-like Operators"> for a list. |
d55a8828 TC |
298 | |
299 | Hexadecimal, octal, or binary, representations in string literals | |
300 | (e.g. '0xff') are not automatically converted to their integer | |
301 | representation. The hex() and oct() functions make these conversions | |
302 | for you. See L<perlfunc/hex> and L<perlfunc/oct> for more details. | |
68dc0745 | 303 | |
5f05dabc | 304 | You can also embed newlines directly in your strings, i.e., they can end |
a0d0e21e LW |
305 | on a different line than they begin. This is nice, but if you forget |
306 | your trailing quote, the error will not be reported until Perl finds | |
307 | another line containing the quote character, which may be much further | |
308 | on in the script. Variable substitution inside strings is limited to | |
d55a8828 | 309 | scalar variables, arrays, and array or hash slices. (In other words, |
b88cefa9 | 310 | names beginning with $ or @, followed by an optional bracketed |
a0d0e21e | 311 | expression as a subscript.) The following code segment prints out "The |
184e9718 | 312 | price is $Z<>100." |
a0d0e21e | 313 | |
692ef166 SF |
314 | $Price = '$100'; # not interpolated |
315 | print "The price is $Price.\n"; # interpolated | |
316 | ||
317 | There is no double interpolation in Perl, so the C<$100> is left as is. | |
a0d0e21e | 318 | |
d55a8828 | 319 | As in some shells, you can enclose the variable name in braces to |
f1cbbd6e GS |
320 | disambiguate it from following alphanumerics (and underscores). |
321 | You must also do | |
d55a8828 TC |
322 | this when interpolating a variable into a string to separate the |
323 | variable name from a following double-colon or an apostrophe, since | |
324 | these would be otherwise treated as a package separator: | |
325 | ||
84f709e7 | 326 | $who = "Larry"; |
d55a8828 TC |
327 | print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n"; |
328 | print "We use ${who}speak when ${who}'s here.\n"; | |
329 | ||
330 | Without the braces, Perl would have looked for a $whospeak, a | |
331 | C<$who::0>, and a C<$who's> variable. The last two would be the | |
332 | $0 and the $s variables in the (presumably) non-existent package | |
333 | C<who>. | |
334 | ||
335 | In fact, an identifier within such curlies is forced to be a string, | |
336 | as is any simple identifier within a hash subscript. Neither need | |
337 | quoting. Our earlier example, C<$days{'Feb'}> can be written as | |
338 | C<$days{Feb}> and the quotes will be assumed automatically. But | |
339 | anything more complicated in the subscript will be interpreted as | |
340 | an expression. | |
341 | ||
692ef166 SF |
342 | =head3 Version Strings |
343 | ||
191d61a7 | 344 | A literal of the form C<v1.20.300.4000> is parsed as a string composed |
6b2463a0 JH |
345 | of characters with the specified ordinals. This form, known as |
346 | v-strings, provides an alternative, more readable way to construct | |
347 | strings, rather than use the somewhat less readable interpolation form | |
348 | C<"\x{1}\x{14}\x{12c}\x{fa0}">. This is useful for representing | |
349 | Unicode strings, and for comparing version "numbers" using the string | |
350 | comparison operators, C<cmp>, C<gt>, C<lt> etc. If there are two or | |
351 | more dots in the literal, the leading C<v> may be omitted. | |
b9c62f5b GS |
352 | |
353 | print v9786; # prints UTF-8 encoded SMILEY, "\x{263a}" | |
354 | print v102.111.111; # prints "foo" | |
355 | print 102.111.111; # same | |
356 | ||
357 | Such literals are accepted by both C<require> and C<use> for | |
191d61a7 GS |
358 | doing a version check. The C<$^V> special variable also contains the |
359 | running Perl interpreter's version in this form. See L<perlvar/$^V>. | |
6b2463a0 JH |
360 | Note that using the v-strings for IPv4 addresses is not portable unless |
361 | you also use the inet_aton()/inet_ntoa() routines of the Socket package. | |
191d61a7 | 362 | |
692ef166 SF |
363 | =head3 Special Literals |
364 | ||
d55a8828 | 365 | The special literals __FILE__, __LINE__, and __PACKAGE__ |
68dc0745 | 366 | represent the current filename, line number, and package name at that |
367 | point in your program. They may be used only as separate tokens; they | |
368 | will not be interpolated into strings. If there is no current package | |
3e92a254 GS |
369 | (due to an empty C<package;> directive), __PACKAGE__ is the undefined |
370 | value. | |
371 | ||
372 | The two control characters ^D and ^Z, and the tokens __END__ and __DATA__ | |
373 | may be used to indicate the logical end of the script before the actual | |
374 | end of file. Any following text is ignored. | |
375 | ||
376 | Text after __DATA__ but may be read via the filehandle C<PACKNAME::DATA>, | |
377 | where C<PACKNAME> is the package that was current when the __DATA__ | |
378 | token was encountered. The filehandle is left open pointing to the | |
379 | contents after __DATA__. It is the program's responsibility to | |
380 | C<close DATA> when it is done reading from it. For compatibility with | |
381 | older scripts written before __DATA__ was introduced, __END__ behaves | |
382 | like __DATA__ in the toplevel script (but not in files loaded with | |
383 | C<require> or C<do>) and leaves the remaining contents of the | |
384 | file accessible via C<main::DATA>. | |
385 | ||
386 | See L<SelfLoader> for more description of __DATA__, and | |
d55a8828 TC |
387 | an example of its use. Note that you cannot read from the DATA |
388 | filehandle in a BEGIN block: the BEGIN block is executed as soon | |
389 | as it is seen (during compilation), at which point the corresponding | |
a00c1fe5 | 390 | __DATA__ (or __END__) token has not yet been seen. |
a0d0e21e | 391 | |
692ef166 SF |
392 | =head3 Barewords |
393 | ||
748a9306 | 394 | A word that has no other interpretation in the grammar will |
a0d0e21e LW |
395 | be treated as if it were a quoted string. These are known as |
396 | "barewords". As with filehandles and labels, a bareword that consists | |
397 | entirely of lowercase letters risks conflict with future reserved | |
9f1b1f2d GS |
398 | words, and if you use the C<use warnings> pragma or the B<-w> switch, |
399 | Perl will warn you about any | |
a0d0e21e LW |
400 | such words. Some people may wish to outlaw barewords entirely. If you |
401 | say | |
402 | ||
403 | use strict 'subs'; | |
404 | ||
405 | then any bareword that would NOT be interpreted as a subroutine call | |
406 | produces a compile-time error instead. The restriction lasts to the | |
54310121 | 407 | end of the enclosing block. An inner block may countermand this |
a0d0e21e LW |
408 | by saying C<no strict 'subs'>. |
409 | ||
692ef166 SF |
410 | =head3 Array Joining Delimiter |
411 | ||
d55a8828 TC |
412 | Arrays and slices are interpolated into double-quoted strings |
413 | by joining the elements with the delimiter specified in the C<$"> | |
692ef166 SF |
414 | variable (C<$LIST_SEPARATOR> if "use English;" is specified), |
415 | space by default. The following are equivalent: | |
a0d0e21e | 416 | |
84f709e7 | 417 | $temp = join($", @ARGV); |
a0d0e21e LW |
418 | system "echo $temp"; |
419 | ||
420 | system "echo @ARGV"; | |
421 | ||
422 | Within search patterns (which also undergo double-quotish substitution) | |
d55a8828 | 423 | there is an unfortunate ambiguity: Is C</$foo[bar]/> to be interpreted as |
a0d0e21e LW |
424 | C</${foo}[bar]/> (where C<[bar]> is a character class for the regular |
425 | expression) or as C</${foo[bar]}/> (where C<[bar]> is the subscript to array | |
426 | @foo)? If @foo doesn't otherwise exist, then it's obviously a | |
427 | character class. If @foo exists, Perl takes a good guess about C<[bar]>, | |
428 | and is almost always right. If it does guess wrong, or if you're just | |
429 | plain paranoid, you can force the correct interpretation with curly | |
d55a8828 | 430 | braces as above. |
a0d0e21e | 431 | |
7e3b091d | 432 | If you're looking for the information on how to use here-documents, |
210b36aa AMS |
433 | which used to be here, that's been moved to |
434 | L<perlop/Quote and Quote-like Operators>. | |
be16fac9 | 435 | |
a0d0e21e LW |
436 | =head2 List value constructors |
437 | ||
438 | List values are denoted by separating individual values by commas | |
439 | (and enclosing the list in parentheses where precedence requires it): | |
440 | ||
441 | (LIST) | |
442 | ||
d55a8828 TC |
443 | In a context not requiring a list value, the value of what appears |
444 | to be a list literal is simply the value of the final element, as | |
445 | with the C comma operator. For example, | |
a0d0e21e | 446 | |
84f709e7 | 447 | @foo = ('cc', '-E', $bar); |
a0d0e21e | 448 | |
d55a8828 | 449 | assigns the entire list value to array @foo, but |
a0d0e21e | 450 | |
84f709e7 | 451 | $foo = ('cc', '-E', $bar); |
a0d0e21e | 452 | |
d55a8828 TC |
453 | assigns the value of variable $bar to the scalar variable $foo. |
454 | Note that the value of an actual array in scalar context is the | |
455 | length of the array; the following assigns the value 3 to $foo: | |
a0d0e21e | 456 | |
84f709e7 | 457 | @foo = ('cc', '-E', $bar); |
7e3b091d | 458 | $foo = @foo; # $foo gets 3 |
a0d0e21e | 459 | |
54310121 | 460 | You may have an optional comma before the closing parenthesis of a |
a0d0e21e LW |
461 | list literal, so that you can say: |
462 | ||
84f709e7 | 463 | @foo = ( |
7e3b091d DA |
464 | 1, |
465 | 2, | |
466 | 3, | |
a0d0e21e LW |
467 | ); |
468 | ||
d55a8828 TC |
469 | To use a here-document to assign an array, one line per element, |
470 | you might use an approach like this: | |
471 | ||
84f709e7 | 472 | @sauces = <<End_Lines =~ m/(\S.*\S)/g; |
7e3b091d DA |
473 | normal tomato |
474 | spicy tomato | |
475 | green chile | |
476 | pesto | |
477 | white wine | |
d55a8828 TC |
478 | End_Lines |
479 | ||
a0d0e21e | 480 | LISTs do automatic interpolation of sublists. That is, when a LIST is |
d55a8828 | 481 | evaluated, each element of the list is evaluated in list context, and |
a0d0e21e | 482 | the resulting list value is interpolated into LIST just as if each |
5a964f20 | 483 | individual element were a member of LIST. Thus arrays and hashes lose their |
a0d0e21e LW |
484 | identity in a LIST--the list |
485 | ||
5a964f20 | 486 | (@foo,@bar,&SomeSub,%glarch) |
a0d0e21e LW |
487 | |
488 | contains all the elements of @foo followed by all the elements of @bar, | |
5a964f20 | 489 | followed by all the elements returned by the subroutine named SomeSub |
d55a8828 | 490 | called in list context, followed by the key/value pairs of %glarch. |
a0d0e21e LW |
491 | To make a list reference that does I<NOT> interpolate, see L<perlref>. |
492 | ||
19799a22 | 493 | The null list is represented by (). Interpolating it in a list |
a0d0e21e LW |
494 | has no effect. Thus ((),(),()) is equivalent to (). Similarly, |
495 | interpolating an array with no elements is the same as if no | |
496 | array had been interpolated at that point. | |
497 | ||
c2689353 | 498 | This interpolation combines with the facts that the opening |
ab1f959b | 499 | and closing parentheses are optional (except when necessary for |
c2689353 NC |
500 | precedence) and lists may end with an optional comma to mean that |
501 | multiple commas within lists are legal syntax. The list C<1,,3> is a | |
502 | concatenation of two lists, C<1,> and C<3>, the first of which ends | |
503 | with that optional comma. C<1,,3> is C<(1,),(3)> is C<1,3> (And | |
504 | similarly for C<1,,,3> is C<(1,),(,),3> is C<1,3> and so on.) Not that | |
505 | we'd advise you to use this obfuscation. | |
506 | ||
a0d0e21e | 507 | A list value may also be subscripted like a normal array. You must |
54310121 | 508 | put the list in parentheses to avoid ambiguity. For example: |
a0d0e21e LW |
509 | |
510 | # Stat returns list value. | |
84f709e7 | 511 | $time = (stat($file))[8]; |
a0d0e21e | 512 | |
4633a7c4 | 513 | # SYNTAX ERROR HERE. |
84f709e7 | 514 | $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES |
4633a7c4 | 515 | |
a0d0e21e | 516 | # Find a hex digit. |
84f709e7 | 517 | $hexdigit = ('a','b','c','d','e','f')[$digit-10]; |
a0d0e21e LW |
518 | |
519 | # A "reverse comma operator". | |
520 | return (pop(@foo),pop(@foo))[0]; | |
521 | ||
d55a8828 TC |
522 | Lists may be assigned to only when each element of the list |
523 | is itself legal to assign to: | |
a0d0e21e | 524 | |
84f709e7 | 525 | ($a, $b, $c) = (1, 2, 3); |
a0d0e21e | 526 | |
84f709e7 | 527 | ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00); |
a0d0e21e | 528 | |
d55a8828 TC |
529 | An exception to this is that you may assign to C<undef> in a list. |
530 | This is useful for throwing away some of the return values of a | |
531 | function: | |
532 | ||
84f709e7 | 533 | ($dev, $ino, undef, undef, $uid, $gid) = stat($file); |
d55a8828 TC |
534 | |
535 | List assignment in scalar context returns the number of elements | |
4633a7c4 LW |
536 | produced by the expression on the right side of the assignment: |
537 | ||
7e3b091d DA |
538 | $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2 |
539 | $x = (($foo,$bar) = f()); # set $x to f()'s return count | |
4633a7c4 | 540 | |
d55a8828 | 541 | This is handy when you want to do a list assignment in a Boolean |
19799a22 | 542 | context, because most list functions return a null list when finished, |
4633a7c4 LW |
543 | which when assigned produces a 0, which is interpreted as FALSE. |
544 | ||
ab1f959b PN |
545 | It's also the source of a useful idiom for executing a function or |
546 | performing an operation in list context and then counting the number of | |
547 | return values, by assigning to an empty list and then using that | |
548 | assignment in scalar context. For example, this code: | |
549 | ||
84f709e7 | 550 | $count = () = $string =~ /\d+/g; |
ab1f959b PN |
551 | |
552 | will place into $count the number of digit groups found in $string. | |
553 | This happens because the pattern match is in list context (since it | |
554 | is being assigned to the empty list), and will therefore return a list | |
555 | of all matching parts of the string. The list assignment in scalar | |
556 | context will translate that into the number of elements (here, the | |
557 | number of times the pattern matched) and assign that to $count. Note | |
558 | that simply using | |
559 | ||
84f709e7 | 560 | $count = $string =~ /\d+/g; |
ab1f959b PN |
561 | |
562 | would not have worked, since a pattern match in scalar context will | |
563 | only return true or false, rather than a count of matches. | |
564 | ||
565 | The final element of a list assignment may be an array or a hash: | |
a0d0e21e | 566 | |
84f709e7 | 567 | ($a, $b, @rest) = split; |
5a964f20 | 568 | my($a, $b, %rest) = @_; |
a0d0e21e | 569 | |
4633a7c4 | 570 | You can actually put an array or hash anywhere in the list, but the first one |
d55a8828 TC |
571 | in the list will soak up all the values, and anything after it will become |
572 | undefined. This may be useful in a my() or local(). | |
a0d0e21e | 573 | |
d55a8828 TC |
574 | A hash can be initialized using a literal list holding pairs of |
575 | items to be interpreted as a key and a value: | |
a0d0e21e LW |
576 | |
577 | # same as map assignment above | |
84f709e7 | 578 | %map = ('red',0x00f,'blue',0x0f0,'green',0xf00); |
a0d0e21e | 579 | |
d55a8828 | 580 | While literal lists and named arrays are often interchangeable, that's |
4633a7c4 LW |
581 | not the case for hashes. Just because you can subscript a list value like |
582 | a normal array does not mean that you can subscript a list value as a | |
583 | hash. Likewise, hashes included as parts of other lists (including | |
584 | parameters lists and return lists from functions) always flatten out into | |
585 | key/value pairs. That's why it's good to use references sometimes. | |
a0d0e21e | 586 | |
c47ff5f1 GS |
587 | It is often more readable to use the C<< => >> operator between key/value |
588 | pairs. The C<< => >> operator is mostly just a more visually distinctive | |
b88cefa9 | 589 | synonym for a comma, but it also arranges for its left-hand operand to be |
5a964f20 | 590 | interpreted as a string--if it's a bareword that would be a legal identifier. |
b88cefa9 | 591 | This makes it nice for initializing hashes: |
a0d0e21e | 592 | |
84f709e7 | 593 | %map = ( |
7e3b091d DA |
594 | red => 0x00f, |
595 | blue => 0x0f0, | |
596 | green => 0xf00, | |
4633a7c4 LW |
597 | ); |
598 | ||
599 | or for initializing hash references to be used as records: | |
600 | ||
84f709e7 | 601 | $rec = { |
7e3b091d DA |
602 | witch => 'Mable the Merciless', |
603 | cat => 'Fluffy the Ferocious', | |
604 | date => '10/31/1776', | |
4633a7c4 LW |
605 | }; |
606 | ||
607 | or for using call-by-named-parameter to complicated functions: | |
608 | ||
84f709e7 | 609 | $field = $query->radio_group( |
7e3b091d | 610 | name => 'group_name', |
4633a7c4 LW |
611 | values => ['eenie','meenie','minie'], |
612 | default => 'meenie', | |
613 | linebreak => 'true', | |
84f709e7 | 614 | labels => \%labels |
4633a7c4 | 615 | ); |
cb1a09d0 AD |
616 | |
617 | Note that just because a hash is initialized in that order doesn't | |
618 | mean that it comes out in that order. See L<perlfunc/sort> for examples | |
619 | of how to arrange for an output ordering. | |
620 | ||
692ef166 SF |
621 | =head2 Subscripts |
622 | ||
623 | An array is subscripted by specifying a dollary sign (C<$>), then the | |
624 | name of the array (without the leading C<@>), then the subscript inside | |
625 | square brackets. For example: | |
626 | ||
627 | @myarray = (5, 50, 500, 5000); | |
628 | print "Element Number 2 is", $myarray[2], "\n"; | |
629 | ||
630 | The array indices start with 0. A negative subscript retrieves its | |
631 | value from the end. In our example, C<$myarray[-1]> would have been | |
632 | 5000, and C<$myarray[-2]> would have been 500. | |
633 | ||
634 | Hash subscripts are similar, only instead of square brackets curly brackets | |
635 | are used. For example: | |
636 | ||
637 | %scientists = | |
638 | ( | |
639 | "Newton" => "Isaac", | |
640 | "Einstein" => "Albert", | |
641 | "Darwin" => "Charles", | |
642 | "Feynman" => "Richard", | |
643 | ); | |
644 | ||
645 | print "Darwin's First Name is ", $scientists{"Darwin"}, "\n"; | |
646 | ||
d55a8828 TC |
647 | =head2 Slices |
648 | ||
56d7751a GS |
649 | A common way to access an array or a hash is one scalar element at a |
650 | time. You can also subscript a list to get a single element from it. | |
d55a8828 | 651 | |
7e3b091d DA |
652 | $whoami = $ENV{"USER"}; # one element from the hash |
653 | $parent = $ISA[0]; # one element from the array | |
654 | $dir = (getpwnam("daemon"))[7]; # likewise, but with list | |
d55a8828 TC |
655 | |
656 | A slice accesses several elements of a list, an array, or a hash | |
56d7751a GS |
657 | simultaneously using a list of subscripts. It's more convenient |
658 | than writing out the individual elements as a list of separate | |
d55a8828 TC |
659 | scalar values. |
660 | ||
7e3b091d DA |
661 | ($him, $her) = @folks[0,-1]; # array slice |
662 | @them = @folks[0 .. 3]; # array slice | |
663 | ($who, $home) = @ENV{"USER", "HOME"}; # hash slice | |
664 | ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice | |
d55a8828 TC |
665 | |
666 | Since you can assign to a list of variables, you can also assign to | |
667 | an array or hash slice. | |
668 | ||
84f709e7 | 669 | @days[3..5] = qw/Wed Thu Fri/; |
d55a8828 | 670 | @colors{'red','blue','green'} |
7e3b091d | 671 | = (0xff0000, 0x0000ff, 0x00ff00); |
d55a8828 TC |
672 | @folks[0, -1] = @folks[-1, 0]; |
673 | ||
674 | The previous assignments are exactly equivalent to | |
675 | ||
84f709e7 JH |
676 | ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/; |
677 | ($colors{'red'}, $colors{'blue'}, $colors{'green'}) | |
7e3b091d | 678 | = (0xff0000, 0x0000ff, 0x00ff00); |
88fd19e3 | 679 | ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]); |
d55a8828 TC |
680 | |
681 | Since changing a slice changes the original array or hash that it's | |
56d7751a GS |
682 | slicing, a C<foreach> construct will alter some--or even all--of the |
683 | values of the array or hash. | |
d55a8828 TC |
684 | |
685 | foreach (@array[ 4 .. 10 ]) { s/peter/paul/ } | |
686 | ||
00cb5da1 | 687 | foreach (@hash{qw[key1 key2]}) { |
7e3b091d DA |
688 | s/^\s+//; # trim leading whitespace |
689 | s/\s+$//; # trim trailing whitespace | |
690 | s/(\w+)/\u\L$1/g; # "titlecase" words | |
d55a8828 TC |
691 | } |
692 | ||
08cd8952 GS |
693 | A slice of an empty list is still an empty list. Thus: |
694 | ||
84f709e7 JH |
695 | @a = ()[1,0]; # @a has no elements |
696 | @b = (@a)[0,1]; # @b has no elements | |
697 | @c = (0,1)[2,3]; # @c has no elements | |
56d7751a GS |
698 | |
699 | But: | |
700 | ||
84f709e7 JH |
701 | @a = (1)[1,0]; # @a has two elements |
702 | @b = (1,undef)[1,0,2]; # @b has three elements | |
08cd8952 | 703 | |
19799a22 GS |
704 | This makes it easy to write loops that terminate when a null list |
705 | is returned: | |
d55a8828 | 706 | |
84f709e7 | 707 | while ( ($home, $user) = (getpwent)[7,0]) { |
7e3b091d | 708 | printf "%-8s %s\n", $user, $home; |
d55a8828 TC |
709 | } |
710 | ||
711 | As noted earlier in this document, the scalar sense of list assignment | |
712 | is the number of elements on the right-hand side of the assignment. | |
19799a22 | 713 | The null list contains no elements, so when the password file is |
d55a8828 TC |
714 | exhausted, the result is 0, not 2. |
715 | ||
716 | If you're confused about why you use an '@' there on a hash slice | |
717 | instead of a '%', think of it like this. The type of bracket (square | |
718 | or curly) governs whether it's an array or a hash being looked at. | |
719 | On the other hand, the leading symbol ('$' or '@') on the array or | |
720 | hash indicates whether you are getting back a singular value (a | |
721 | scalar) or a plural one (a list). | |
722 | ||
5f05dabc | 723 | =head2 Typeglobs and Filehandles |
cb1a09d0 AD |
724 | |
725 | Perl uses an internal type called a I<typeglob> to hold an entire | |
726 | symbol table entry. The type prefix of a typeglob is a C<*>, because | |
54310121 | 727 | it represents all types. This used to be the preferred way to |
cb1a09d0 | 728 | pass arrays and hashes by reference into a function, but now that |
5a964f20 TC |
729 | we have real references, this is seldom needed. |
730 | ||
731 | The main use of typeglobs in modern Perl is create symbol table aliases. | |
732 | This assignment: | |
733 | ||
734 | *this = *that; | |
735 | ||
736 | makes $this an alias for $that, @this an alias for @that, %this an alias | |
737 | for %that, &this an alias for &that, etc. Much safer is to use a reference. | |
738 | This: | |
5f05dabc | 739 | |
5a964f20 TC |
740 | local *Here::blue = \$There::green; |
741 | ||
742 | temporarily makes $Here::blue an alias for $There::green, but doesn't | |
743 | make @Here::blue an alias for @There::green, or %Here::blue an alias for | |
744 | %There::green, etc. See L<perlmod/"Symbol Tables"> for more examples | |
745 | of this. Strange though this may seem, this is the basis for the whole | |
84f709e7 | 746 | module import/export system. |
5a964f20 | 747 | |
d55a8828 | 748 | Another use for typeglobs is to pass filehandles into a function or |
5a964f20 TC |
749 | to create new filehandles. If you need to use a typeglob to save away |
750 | a filehandle, do it this way: | |
5f05dabc | 751 | |
84f709e7 | 752 | $fh = *STDOUT; |
5f05dabc | 753 | |
754 | or perhaps as a real reference, like this: | |
755 | ||
84f709e7 | 756 | $fh = \*STDOUT; |
5f05dabc | 757 | |
5a964f20 TC |
758 | See L<perlsub> for examples of using these as indirect filehandles |
759 | in functions. | |
760 | ||
761 | Typeglobs are also a way to create a local filehandle using the local() | |
762 | operator. These last until their block is exited, but may be passed back. | |
763 | For example: | |
5f05dabc | 764 | |
765 | sub newopen { | |
7e3b091d DA |
766 | my $path = shift; |
767 | local *FH; # not my! | |
768 | open (FH, $path) or return undef; | |
769 | return *FH; | |
5f05dabc | 770 | } |
84f709e7 | 771 | $fh = newopen('/etc/passwd'); |
5f05dabc | 772 | |
d55a8828 | 773 | Now that we have the C<*foo{THING}> notation, typeglobs aren't used as much |
5a964f20 TC |
774 | for filehandle manipulations, although they're still needed to pass brand |
775 | new file and directory handles into or out of functions. That's because | |
d55a8828 TC |
776 | C<*HANDLE{IO}> only works if HANDLE has already been used as a handle. |
777 | In other words, C<*FH> must be used to create new symbol table entries; | |
778 | C<*foo{THING}> cannot. When in doubt, use C<*FH>. | |
779 | ||
36392fcf GS |
780 | All functions that are capable of creating filehandles (open(), |
781 | opendir(), pipe(), socketpair(), sysopen(), socket(), and accept()) | |
782 | automatically create an anonymous filehandle if the handle passed to | |
783 | them is an uninitialized scalar variable. This allows the constructs | |
784 | such as C<open(my $fh, ...)> and C<open(local $fh,...)> to be used to | |
785 | create filehandles that will conveniently be closed automatically when | |
786 | the scope ends, provided there are no other references to them. This | |
787 | largely eliminates the need for typeglobs when opening filehandles | |
788 | that must be passed around, as in the following example: | |
789 | ||
790 | sub myopen { | |
84f709e7 | 791 | open my $fh, "@_" |
7e3b091d DA |
792 | or die "Can't open '@_': $!"; |
793 | return $fh; | |
36392fcf GS |
794 | } |
795 | ||
796 | { | |
797 | my $f = myopen("</etc/motd"); | |
7e3b091d DA |
798 | print <$f>; |
799 | # $f implicitly closed here | |
36392fcf GS |
800 | } |
801 | ||
b92795fe AMS |
802 | Note that if an initialized scalar variable is used instead the |
803 | result is different: C<my $fh='zzz'; open($fh, ...)> is equivalent | |
804 | to C<open( *{'zzz'}, ...)>. | |
d83fe814 AT |
805 | C<use strict 'refs'> forbids such practice. |
806 | ||
d55a8828 TC |
807 | Another way to create anonymous filehandles is with the Symbol |
808 | module or with the IO::Handle module and its ilk. These modules | |
809 | have the advantage of not hiding different types of the same name | |
810 | during the local(). See the bottom of L<perlfunc/open()> for an | |
811 | example. | |
812 | ||
813 | =head1 SEE ALSO | |
814 | ||
815 | See L<perlvar> for a description of Perl's built-in variables and | |
816 | a discussion of legal variable names. See L<perlref>, L<perlsub>, | |
817 | and L<perlmod/"Symbol Tables"> for more discussion on typeglobs and | |
818 | the C<*foo{THING}> syntax. |