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