| 1 | =head1 NAME |
| 2 | |
| 3 | perldata - Perl data structures |
| 4 | |
| 5 | =head1 DESCRIPTION |
| 6 | |
| 7 | =head2 Variable names |
| 8 | |
| 9 | Perl has three data structures: scalars, arrays of scalars, and |
| 10 | associative arrays of scalars, known as "hashes". Normal arrays are |
| 11 | indexed by number, starting with 0. (Negative subscripts count from |
| 12 | the end.) Hash arrays are indexed by string. |
| 13 | |
| 14 | Scalar values are always named with '$', even when referring to a scalar |
| 15 | that is part of an array. It works like the English word "the". Thus |
| 16 | we 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 | |
| 23 | but entire arrays or array slices are denoted by '@', which works much like |
| 24 | the 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 | |
| 30 | and entire hashes are denoted by '%': |
| 31 | |
| 32 | %days # (key1, val1, key2, val2 ...) |
| 33 | |
| 34 | In addition, subroutines are named with an initial '&', though this is |
| 35 | optional when it's otherwise unambiguous (just as "do" is often |
| 36 | redundant in English). Symbol table entries can be named with an |
| 37 | initial '*', but you don't really care about that yet. |
| 38 | |
| 39 | Every variable type has its own namespace. You can, without fear of |
| 40 | conflict, 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). |
| 42 | This means that $foo and @foo are two different variables. It also |
| 43 | means that C<$foo[1]> is a part of @foo, not a part of $foo. This may |
| 44 | seem a bit weird, but that's okay, because it is weird. |
| 45 | |
| 46 | Since variable and array references always start with '$', '@', or '%', |
| 47 | the "reserved" words aren't in fact reserved with respect to variable |
| 48 | names. (They ARE reserved with respect to labels and filehandles, |
| 49 | however, which don't have an initial special character. You can't have |
| 50 | a filehandle named "log", for instance. Hint: you could say |
| 51 | C<open(LOG,'logfile')> rather than C<open(log,'logfile')>. Using uppercase |
| 52 | filehandles also improves readability and protects you from conflict |
| 53 | with future reserved words.) Case I<IS> significant--"FOO", "Foo" and |
| 54 | "foo" are all different names. Names that start with a letter or |
| 55 | underscore may also contain digits and underscores. |
| 56 | |
| 57 | It is possible to replace such an alphanumeric name with an expression |
| 58 | that returns a reference to an object of that type. For a description |
| 59 | of this, see L<perlref>. |
| 60 | |
| 61 | Names that start with a digit may only contain more digits. Names |
| 62 | which do not start with a letter, underscore, or digit are limited to |
| 63 | one character, e.g. "$%" or "$$". (Most of these one character names |
| 64 | have a predefined significance to Perl. For instance, $$ is the |
| 65 | current process id.) |
| 66 | |
| 67 | =head2 Context |
| 68 | |
| 69 | The interpretation of operations and values in Perl sometimes depends |
| 70 | on the requirements of the context around the operation or value. |
| 71 | There are two major contexts: scalar and list. Certain operations |
| 72 | return list values in contexts wanting a list, and scalar values |
| 73 | otherwise. (If this is true of an operation it will be mentioned in |
| 74 | the documentation for that operation.) In other words, Perl overloads |
| 75 | certain operations based on whether the expected return value is |
| 76 | singular or plural. (Some words in English work this way, like "fish" |
| 77 | and "sheep".) |
| 78 | |
| 79 | In a reciprocal fashion, an operation provides either a scalar or a |
| 80 | list context to each of its arguments. For example, if you say |
| 81 | |
| 82 | int( <STDIN> ) |
| 83 | |
| 84 | the integer operation provides a scalar context for the <STDIN> |
| 85 | operator, which responds by reading one line from STDIN and passing it |
| 86 | back to the integer operation, which will then find the integer value |
| 87 | of that line and return that. If, on the other hand, you say |
| 88 | |
| 89 | sort( <STDIN> ) |
| 90 | |
| 91 | then the sort operation provides a list context for <STDIN>, which |
| 92 | will proceed to read every line available up to the end of file, and |
| 93 | pass that list of lines back to the sort routine, which will then |
| 94 | sort those lines and return them as a list to whatever the context |
| 95 | of the sort was. |
| 96 | |
| 97 | Assignment is a little bit special in that it uses its left argument to |
| 98 | determine the context for the right argument. Assignment to a scalar |
| 99 | evaluates the righthand side in a scalar context, while assignment to |
| 100 | an array or array slice evaluates the righthand side in a list |
| 101 | context. Assignment to a list also evaluates the righthand side in a |
| 102 | list context. |
| 103 | |
| 104 | User defined subroutines may choose to care whether they are being |
| 105 | called in a scalar or list context, but most subroutines do not |
| 106 | need to care, because scalars are automatically interpolated into |
| 107 | lists. See L<perlfunc/wantarray>. |
| 108 | |
| 109 | =head2 Scalar values |
| 110 | |
| 111 | Scalar variables may contain various kinds of singular data, such as |
| 112 | numbers, strings and references. In general, conversion from one form |
| 113 | to another is transparent. (A scalar may not contain multiple values, |
| 114 | but may contain a reference to an array or hash containing multiple |
| 115 | values.) Because of the automatic conversion of scalars, operations and |
| 116 | functions that return scalars don't need to care (and, in fact, can't |
| 117 | care) whether the context is looking for a string or a number. |
| 118 | |
| 119 | A scalar value is interpreted as TRUE in the Boolean sense if it is not |
| 120 | the null string or the number 0 (or its string equivalent, "0"). The |
| 121 | Boolean context is just a special kind of scalar context. |
| 122 | |
| 123 | There are actually two varieties of null scalars: defined and |
| 124 | undefined. Undefined null scalars are returned when there is no real |
| 125 | value for something, such as when there was an error, or at end of |
| 126 | file, or when you refer to an uninitialized variable or element of an |
| 127 | array. An undefined null scalar may become defined the first time you |
| 128 | use it as if it were defined, but prior to that you can use the |
| 129 | defined() operator to determine whether the value is defined or not. |
| 130 | |
| 131 | The length of an array is a scalar value. You may find the length of |
| 132 | array @days by evaluating C<$#days>, as in B<csh>. (Actually, it's not |
| 133 | the length of the array, it's the subscript of the last element, since |
| 134 | there is (ordinarily) a 0th element.) Assigning to C<$#days> changes the |
| 135 | length of the array. Shortening an array by this method destroys |
| 136 | intervening values. Lengthening an array that was previously shortened |
| 137 | I<NO LONGER> recovers the values that were in those elements. (It used to |
| 138 | in Perl 4, but we had to break this make to make sure destructors were |
| 139 | called when expected.) You can also gain some measure of efficiency by |
| 140 | preextending an array that is going to get big. (You can also extend |
| 141 | an array by assigning to an element that is off the end of the array.) |
| 142 | You can truncate an array down to nothing by assigning the null list () |
| 143 | to it. The following are equivalent: |
| 144 | |
| 145 | @whatever = (); |
| 146 | $#whatever = $[ - 1; |
| 147 | |
| 148 | If you evaluate a named array in a scalar context, it returns the length of |
| 149 | the array. (Note that this is not true of lists, which return the |
| 150 | last value, like the C comma operator.) The following is always true: |
| 151 | |
| 152 | scalar(@whatever) == $#whatever - $[ + 1; |
| 153 | |
| 154 | Version 5 of Perl changed the semantics of $[: files that don't set |
| 155 | the value of $[ no longer need to worry about whether another |
| 156 | file changed its value. (In other words, use of $[ is deprecated.) |
| 157 | So in general you can just assume that |
| 158 | |
| 159 | scalar(@whatever) == $#whatever + 1; |
| 160 | |
| 161 | If you evaluate a hash in a scalar context, it returns a value which is |
| 162 | true if and only if the hash contains any key/value pairs. (If there |
| 163 | are any key/value pairs, the value returned is a string consisting of |
| 164 | the number of used buckets and the number of allocated buckets, separated |
| 165 | by 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. |
| 167 | For example, you stick 10,000 things in a hash, but evaluating %HASH in |
| 168 | scalar context reveals "1/16", which means only one out of sixteen buckets |
| 169 | has been touched, and presumably contains all 10,000 of your items. This |
| 170 | isn't supposed to happen.) |
| 171 | |
| 172 | =head2 Scalar value constructors |
| 173 | |
| 174 | Numeric literals are specified in any of the customary floating point or |
| 175 | integer 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 | |
| 185 | String literals are delimited by either single or double quotes. They |
| 186 | work much like shell quotes: double-quoted string literals are subject |
| 187 | to backslash and variable substitution; single-quoted strings are not |
| 188 | (except for "C<\'>" and "C<\\>"). The usual Unix backslash rules apply for making |
| 189 | characters such as newline, tab, etc., as well as some more exotic |
| 190 | forms. See L<perlop/qq> for a list. |
| 191 | |
| 192 | You can also embed newlines directly in your strings, i.e. they can end |
| 193 | on a different line than they begin. This is nice, but if you forget |
| 194 | your trailing quote, the error will not be reported until Perl finds |
| 195 | another line containing the quote character, which may be much further |
| 196 | on in the script. Variable substitution inside strings is limited to |
| 197 | scalar variables, arrays, and array slices. (In other words, |
| 198 | identifiers beginning with $ or @, followed by an optional bracketed |
| 199 | expression as a subscript.) The following code segment prints out "The |
| 200 | price is $100." |
| 201 | |
| 202 | $Price = '$100'; # not interpreted |
| 203 | print "The price is $Price.\n"; # interpreted |
| 204 | |
| 205 | As in some shells, you can put curly brackets around the identifier to |
| 206 | delimit it from following alphanumerics. In fact, an identifier |
| 207 | within such curlies is forced to be a string, as is any single |
| 208 | identifier within a hash subscript. Our earlier example, |
| 209 | |
| 210 | $days{'Feb'} |
| 211 | |
| 212 | can be written as |
| 213 | |
| 214 | $days{Feb} |
| 215 | |
| 216 | and the quotes will be assumed automatically. But anything more complicated |
| 217 | in the subscript will be interpreted as an expression. |
| 218 | |
| 219 | Note that a |
| 220 | single-quoted string must be separated from a preceding word by a |
| 221 | space, since single quote is a valid (though deprecated) character in |
| 222 | an identifier (see L<perlmod/Packages>). |
| 223 | |
| 224 | Two special literals are __LINE__ and __FILE__, which represent the |
| 225 | current line number and filename at that point in your program. They |
| 226 | may only be used as separate tokens; they will not be interpolated into |
| 227 | strings. In addition, the token __END__ may be used to indicate the |
| 228 | logical end of the script before the actual end of file. Any following |
| 229 | text is ignored, but may be read via the DATA filehandle. (The DATA |
| 230 | filehandle may read data only from the main script, but not from any |
| 231 | required file or evaluated string.) The two control characters ^D and |
| 232 | ^Z are synonyms for __END__. |
| 233 | |
| 234 | A word that has no other interpretation in the grammar will |
| 235 | be treated as if it were a quoted string. These are known as |
| 236 | "barewords". As with filehandles and labels, a bareword that consists |
| 237 | entirely of lowercase letters risks conflict with future reserved |
| 238 | words, and if you use the B<-w> switch, Perl will warn you about any |
| 239 | such words. Some people may wish to outlaw barewords entirely. If you |
| 240 | say |
| 241 | |
| 242 | use strict 'subs'; |
| 243 | |
| 244 | then any bareword that would NOT be interpreted as a subroutine call |
| 245 | produces a compile-time error instead. The restriction lasts to the |
| 246 | end of the enclosing block. An inner block may countermand this |
| 247 | by saying C<no strict 'subs'>. |
| 248 | |
| 249 | Array variables are interpolated into double-quoted strings by joining all |
| 250 | the elements of the array with the delimiter specified in the C<$"> |
| 251 | variable, space by default. The following are equivalent: |
| 252 | |
| 253 | $temp = join($",@ARGV); |
| 254 | system "echo $temp"; |
| 255 | |
| 256 | system "echo @ARGV"; |
| 257 | |
| 258 | Within search patterns (which also undergo double-quotish substitution) |
| 259 | there is a bad ambiguity: Is C</$foo[bar]/> to be interpreted as |
| 260 | C</${foo}[bar]/> (where C<[bar]> is a character class for the regular |
| 261 | expression) or as C</${foo[bar]}/> (where C<[bar]> is the subscript to array |
| 262 | @foo)? If @foo doesn't otherwise exist, then it's obviously a |
| 263 | character class. If @foo exists, Perl takes a good guess about C<[bar]>, |
| 264 | and is almost always right. If it does guess wrong, or if you're just |
| 265 | plain paranoid, you can force the correct interpretation with curly |
| 266 | brackets as above. |
| 267 | |
| 268 | A line-oriented form of quoting is based on the shell "here-doc" syntax. |
| 269 | Following a C<E<lt>E<lt>> you specify a string to terminate the quoted material, |
| 270 | and all lines following the current line down to the terminating string |
| 271 | are the value of the item. The terminating string may be either an |
| 272 | identifier (a word), or some quoted text. If quoted, the type of |
| 273 | quotes you use determines the treatment of the text, just as in regular |
| 274 | quoting. An unquoted identifier works like double quotes. There must |
| 275 | be no space between the C<E<lt>E<lt>> and the identifier. (If you put a space it |
| 276 | will be treated as a null identifier, which is valid, and matches the |
| 277 | first blank line--see the Merry Christmas example below.) The terminating |
| 278 | string must appear by itself (unquoted and with no surrounding |
| 279 | whitespace) on the terminating line. |
| 280 | |
| 281 | print <<EOF; # same as above |
| 282 | The price is $Price. |
| 283 | EOF |
| 284 | |
| 285 | print <<"EOF"; # same as above |
| 286 | The price is $Price. |
| 287 | EOF |
| 288 | |
| 289 | print << x 10; # Legal but discouraged. Use <<"". |
| 290 | Merry Christmas! |
| 291 | |
| 292 | print <<`EOC`; # execute commands |
| 293 | echo hi there |
| 294 | echo lo there |
| 295 | EOC |
| 296 | |
| 297 | print <<"foo", <<"bar"; # you can stack them |
| 298 | I said foo. |
| 299 | foo |
| 300 | I said bar. |
| 301 | bar |
| 302 | |
| 303 | myfunc(<<"THIS", 23, <<'THAT''); |
| 304 | Here's a line |
| 305 | or two. |
| 306 | THIS |
| 307 | and here another. |
| 308 | THAT |
| 309 | |
| 310 | Just don't forget that you have to put a semicolon on the end |
| 311 | to finish the statement, as Perl doesn't know you're not going to |
| 312 | try to do this: |
| 313 | |
| 314 | print <<ABC |
| 315 | 179231 |
| 316 | ABC |
| 317 | + 20; |
| 318 | |
| 319 | |
| 320 | =head2 List value constructors |
| 321 | |
| 322 | List values are denoted by separating individual values by commas |
| 323 | (and enclosing the list in parentheses where precedence requires it): |
| 324 | |
| 325 | (LIST) |
| 326 | |
| 327 | In a context not requiring a list value, the value of the list |
| 328 | literal is the value of the final element, as with the C comma operator. |
| 329 | For example, |
| 330 | |
| 331 | @foo = ('cc', '-E', $bar); |
| 332 | |
| 333 | assigns the entire list value to array foo, but |
| 334 | |
| 335 | $foo = ('cc', '-E', $bar); |
| 336 | |
| 337 | assigns the value of variable bar to variable foo. Note that the value |
| 338 | of an actual array in a scalar context is the length of the array; the |
| 339 | following assigns to $foo the value 3: |
| 340 | |
| 341 | @foo = ('cc', '-E', $bar); |
| 342 | $foo = @foo; # $foo gets 3 |
| 343 | |
| 344 | You may have an optional comma before the closing parenthesis of an |
| 345 | list literal, so that you can say: |
| 346 | |
| 347 | @foo = ( |
| 348 | 1, |
| 349 | 2, |
| 350 | 3, |
| 351 | ); |
| 352 | |
| 353 | LISTs do automatic interpolation of sublists. That is, when a LIST is |
| 354 | evaluated, each element of the list is evaluated in a list context, and |
| 355 | the resulting list value is interpolated into LIST just as if each |
| 356 | individual element were a member of LIST. Thus arrays lose their |
| 357 | identity in a LIST--the list |
| 358 | |
| 359 | (@foo,@bar,&SomeSub) |
| 360 | |
| 361 | contains all the elements of @foo followed by all the elements of @bar, |
| 362 | followed by all the elements returned by the subroutine named SomeSub. |
| 363 | To make a list reference that does I<NOT> interpolate, see L<perlref>. |
| 364 | |
| 365 | The null list is represented by (). Interpolating it in a list |
| 366 | has no effect. Thus ((),(),()) is equivalent to (). Similarly, |
| 367 | interpolating an array with no elements is the same as if no |
| 368 | array had been interpolated at that point. |
| 369 | |
| 370 | A list value may also be subscripted like a normal array. You must |
| 371 | put the list in parentheses to avoid ambiguity. Examples: |
| 372 | |
| 373 | # Stat returns list value. |
| 374 | $time = (stat($file))[8]; |
| 375 | |
| 376 | # Find a hex digit. |
| 377 | $hexdigit = ('a','b','c','d','e','f')[$digit-10]; |
| 378 | |
| 379 | # A "reverse comma operator". |
| 380 | return (pop(@foo),pop(@foo))[0]; |
| 381 | |
| 382 | Lists may be assigned to if and only if each element of the list |
| 383 | is legal to assign to: |
| 384 | |
| 385 | ($a, $b, $c) = (1, 2, 3); |
| 386 | |
| 387 | ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00); |
| 388 | |
| 389 | The final element may be an array or a hash: |
| 390 | |
| 391 | ($a, $b, @rest) = split; |
| 392 | local($a, $b, %rest) = @_; |
| 393 | |
| 394 | You can actually put an array anywhere in the list, but the first array |
| 395 | in the list will soak up all the values, and anything after it will get |
| 396 | a null value. This may be useful in a local() or my(). |
| 397 | |
| 398 | A hash literal contains pairs of values to be interpreted |
| 399 | as a key and a value: |
| 400 | |
| 401 | # same as map assignment above |
| 402 | %map = ('red',0x00f,'blue',0x0f0,'green',0xf00); |
| 403 | |
| 404 | It is often more readable to use the C<=E<gt>> operator between key/value pairs |
| 405 | (the C<=E<gt>> operator is actually nothing more than a more visually |
| 406 | distinctive synonym for a comma): |
| 407 | |
| 408 | %map = ( |
| 409 | 'red' => 0x00f, |
| 410 | 'blue' => 0x0f0, |
| 411 | 'green' => 0xf00, |
| 412 | ); |
| 413 | |
| 414 | Array assignment in a scalar context returns the number of elements |
| 415 | produced by the expression on the right side of the assignment: |
| 416 | |
| 417 | $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2 |
| 418 | |
| 419 | This is very handy when you want to do a list assignment in a Boolean |
| 420 | context, since most list functions return a null list when finished, |
| 421 | which when assigned produces a 0, which is interpreted as FALSE. |