1N/A=head1 NAME
1N/A
1N/Aperldata - Perl data types
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/A=head2 Variable names
1N/A
1N/APerl has three built-in data types: scalars, arrays of scalars, and
1N/Aassociative arrays of scalars, known as "hashes". A scalar is a
1N/Asingle string (of any size, limited only by the available memory),
1N/Anumber, or a reference to something (which will be discussed
1N/Ain L<perlref>). Normal arrays are ordered lists of scalars indexed
1N/Aby number, starting with 0. Hashes are unordered collections of scalar
1N/Avalues indexed by their associated string key.
1N/A
1N/AValues are usually referred to by name, or through a named reference.
1N/AThe first character of the name tells you to what sort of data
1N/Astructure it refers. The rest of the name tells you the particular
1N/Avalue to which it refers. Usually this name is a single I<identifier>,
1N/Athat is, a string beginning with a letter or underscore, and
1N/Acontaining letters, underscores, and digits. In some cases, it may
1N/Abe a chain of identifiers, separated by C<::> (or by the slightly
1N/Aarchaic C<'>); all but the last are interpreted as names of packages,
1N/Ato locate the namespace in which to look up the final identifier
1N/A(see L<perlmod/Packages> for details). It's possible to substitute
1N/Afor a simple identifier, an expression that produces a reference
1N/Ato the value at runtime. This is described in more detail below
1N/Aand in L<perlref>.
1N/A
1N/APerl also has its own built-in variables whose names don't follow
1N/Athese rules. They have strange names so they don't accidentally
1N/Acollide with one of your normal variables. Strings that match
1N/Aparenthesized parts of a regular expression are saved under names
1N/Acontaining only digits after the C<$> (see L<perlop> and L<perlre>).
1N/AIn addition, several special variables that provide windows into
1N/Athe inner working of Perl have names containing punctuation characters
1N/Aand control characters. These are documented in L<perlvar>.
1N/A
1N/AScalar values are always named with '$', even when referring to a
1N/Ascalar that is part of an array or a hash. The '$' symbol works
1N/Asemantically like the English word "the" in that it indicates a
1N/Asingle value is expected.
1N/A
1N/A $days # the simple scalar value "days"
1N/A $days[28] # the 29th element of array @days
1N/A $days{'Feb'} # the 'Feb' value from hash %days
1N/A $#days # the last index of array @days
1N/A
1N/AEntire arrays (and slices of arrays and hashes) are denoted by '@',
1N/Awhich works much like the word "these" or "those" does in English,
1N/Ain that it indicates multiple values are expected.
1N/A
1N/A @days # ($days[0], $days[1],... $days[n])
1N/A @days[3,4,5] # same as ($days[3],$days[4],$days[5])
1N/A @days{'a','c'} # same as ($days{'a'},$days{'c'})
1N/A
1N/AEntire hashes are denoted by '%':
1N/A
1N/A %days # (key1, val1, key2, val2 ...)
1N/A
1N/AIn addition, subroutines are named with an initial '&', though this
1N/Ais optional when unambiguous, just as the word "do" is often redundant
1N/Ain English. Symbol table entries can be named with an initial '*',
1N/Abut you don't really care about that yet (if ever :-).
1N/A
1N/AEvery variable type has its own namespace, as do several
1N/Anon-variable identifiers. This means that you can, without fear
1N/Aof conflict, use the same name for a scalar variable, an array, or
1N/Aa hash--or, for that matter, for a filehandle, a directory handle, a
1N/Asubroutine name, a format name, or a label. This means that $foo
1N/Aand @foo are two different variables. It also means that C<$foo[1]>
1N/Ais a part of @foo, not a part of $foo. This may seem a bit weird,
1N/Abut that's okay, because it is weird.
1N/A
1N/ABecause variable references always start with '$', '@', or '%', the
1N/A"reserved" words aren't in fact reserved with respect to variable
1N/Anames. They I<are> reserved with respect to labels and filehandles,
1N/Ahowever, which don't have an initial special character. You can't
1N/Ahave a filehandle named "log", for instance. Hint: you could say
1N/AC<open(LOG,'logfile')> rather than C<open(log,'logfile')>. Using
1N/Auppercase filehandles also improves readability and protects you
1N/Afrom conflict with future reserved words. Case I<is> significant--"FOO",
1N/A"Foo", and "foo" are all different names. Names that start with a
1N/Aletter or underscore may also contain digits and underscores.
1N/A
1N/AIt is possible to replace such an alphanumeric name with an expression
1N/Athat returns a reference to the appropriate type. For a description
1N/Aof this, see L<perlref>.
1N/A
1N/ANames that start with a digit may contain only more digits. Names
1N/Athat do not start with a letter, underscore, digit or a caret (i.e.
1N/Aa control character) are limited to one character, e.g., C<$%> or
1N/AC<$$>. (Most of these one character names have a predefined
1N/Asignificance to Perl. For instance, C<$$> is the current process
1N/Aid.)
1N/A
1N/A=head2 Context
1N/A
1N/AThe interpretation of operations and values in Perl sometimes depends
1N/Aon the requirements of the context around the operation or value.
1N/AThere are two major contexts: list and scalar. Certain operations
1N/Areturn list values in contexts wanting a list, and scalar values
1N/Aotherwise. If this is true of an operation it will be mentioned in
1N/Athe documentation for that operation. In other words, Perl overloads
1N/Acertain operations based on whether the expected return value is
1N/Asingular or plural. Some words in English work this way, like "fish"
1N/Aand "sheep".
1N/A
1N/AIn a reciprocal fashion, an operation provides either a scalar or a
1N/Alist context to each of its arguments. For example, if you say
1N/A
1N/A int( <STDIN> )
1N/A
1N/Athe integer operation provides scalar context for the <>
1N/Aoperator, which responds by reading one line from STDIN and passing it
1N/Aback to the integer operation, which will then find the integer value
1N/Aof that line and return that. If, on the other hand, you say
1N/A
1N/A sort( <STDIN> )
1N/A
1N/Athen the sort operation provides list context for <>, which
1N/Awill proceed to read every line available up to the end of file, and
1N/Apass that list of lines back to the sort routine, which will then
1N/Asort those lines and return them as a list to whatever the context
1N/Aof the sort was.
1N/A
1N/AAssignment is a little bit special in that it uses its left argument
1N/Ato determine the context for the right argument. Assignment to a
1N/Ascalar evaluates the right-hand side in scalar context, while
1N/Aassignment to an array or hash evaluates the righthand side in list
1N/Acontext. Assignment to a list (or slice, which is just a list
1N/Aanyway) also evaluates the righthand side in list context.
1N/A
1N/AWhen you use the C<use warnings> pragma or Perl's B<-w> command-line
1N/Aoption, you may see warnings
1N/Aabout useless uses of constants or functions in "void context".
1N/AVoid context just means the value has been discarded, such as a
1N/Astatement containing only C<"fred";> or C<getpwuid(0);>. It still
1N/Acounts as scalar context for functions that care whether or not
1N/Athey're being called in list context.
1N/A
1N/AUser-defined subroutines may choose to care whether they are being
1N/Acalled in a void, scalar, or list context. Most subroutines do not
1N/Aneed to bother, though. That's because both scalars and lists are
1N/Aautomatically interpolated into lists. See L<perlfunc/wantarray>
1N/Afor how you would dynamically discern your function's calling
1N/Acontext.
1N/A
1N/A=head2 Scalar values
1N/A
1N/AAll data in Perl is a scalar, an array of scalars, or a hash of
1N/Ascalars. A scalar may contain one single value in any of three
1N/Adifferent flavors: a number, a string, or a reference. In general,
1N/Aconversion from one form to another is transparent. Although a
1N/Ascalar may not directly hold multiple values, it may contain a
1N/Areference to an array or hash which in turn contains multiple values.
1N/A
1N/AScalars aren't necessarily one thing or another. There's no place
1N/Ato declare a scalar variable to be of type "string", type "number",
1N/Atype "reference", or anything else. Because of the automatic
1N/Aconversion of scalars, operations that return scalars don't need
1N/Ato care (and in fact, cannot care) whether their caller is looking
1N/Afor a string, a number, or a reference. Perl is a contextually
1N/Apolymorphic language whose scalars can be strings, numbers, or
1N/Areferences (which includes objects). Although strings and numbers
1N/Aare considered pretty much the same thing for nearly all purposes,
1N/Areferences are strongly-typed, uncastable pointers with builtin
1N/Areference-counting and destructor invocation.
1N/A
1N/AA scalar value is interpreted as TRUE in the Boolean sense if it is not
1N/Athe null string or the number 0 (or its string equivalent, "0"). The
1N/ABoolean context is just a special kind of scalar context where no
1N/Aconversion to a string or a number is ever performed.
1N/A
1N/AThere are actually two varieties of null strings (sometimes referred
1N/Ato as "empty" strings), a defined one and an undefined one. The
1N/Adefined version is just a string of length zero, such as C<"">.
1N/AThe undefined version is the value that indicates that there is
1N/Ano real value for something, such as when there was an error, or
1N/Aat end of file, or when you refer to an uninitialized variable or
1N/Aelement of an array or hash. Although in early versions of Perl,
1N/Aan undefined scalar could become defined when first used in a
1N/Aplace expecting a defined value, this no longer happens except for
1N/Arare cases of autovivification as explained in L<perlref>. You can
1N/Ause the defined() operator to determine whether a scalar value is
1N/Adefined (this has no meaning on arrays or hashes), and the undef()
1N/Aoperator to produce an undefined value.
1N/A
1N/ATo find out whether a given string is a valid non-zero number, it's
1N/Asometimes enough to test it against both numeric 0 and also lexical
1N/A"0" (although this will cause noises if warnings are on). That's
1N/Abecause strings that aren't numbers count as 0, just as they do in B<awk>:
1N/A
1N/A if ($str == 0 && $str ne "0") {
1N/A warn "That doesn't look like a number";
1N/A }
1N/A
1N/AThat method may be best because otherwise you won't treat IEEE
1N/Anotations like C<NaN> or C<Infinity> properly. At other times, you
1N/Amight prefer to determine whether string data can be used numerically
1N/Aby calling the POSIX::strtod() function or by inspecting your string
1N/Awith a regular expression (as documented in L<perlre>).
1N/A
1N/A warn "has nondigits" if /\D/;
1N/A warn "not a natural number" unless /^\d+$/; # rejects -3
1N/A warn "not an integer" unless /^-?\d+$/; # rejects +3
1N/A warn "not an integer" unless /^[+-]?\d+$/;
1N/A warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
1N/A warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
1N/A warn "not a C float"
1N/A unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
1N/A
1N/AThe length of an array is a scalar value. You may find the length
1N/Aof array @days by evaluating C<$#days>, as in B<csh>. However, this
1N/Aisn't the length of the array; it's the subscript of the last element,
1N/Awhich is a different value since there is ordinarily a 0th element.
1N/AAssigning to C<$#days> actually changes the length of the array.
1N/AShortening an array this way destroys intervening values. Lengthening
1N/Aan array that was previously shortened does not recover values
1N/Athat were in those elements. (It used to do so in Perl 4, but we
1N/Ahad to break this to make sure destructors were called when expected.)
1N/A
1N/AYou can also gain some minuscule measure of efficiency by pre-extending
1N/Aan array that is going to get big. You can also extend an array
1N/Aby assigning to an element that is off the end of the array. You
1N/Acan truncate an array down to nothing by assigning the null list
1N/A() to it. The following are equivalent:
1N/A
1N/A @whatever = ();
1N/A $#whatever = -1;
1N/A
1N/AIf you evaluate an array in scalar context, it returns the length
1N/Aof the array. (Note that this is not true of lists, which return
1N/Athe last value, like the C comma operator, nor of built-in functions,
1N/Awhich return whatever they feel like returning.) The following is
1N/Aalways true:
1N/A
1N/A scalar(@whatever) == $#whatever - $[ + 1;
1N/A
1N/AVersion 5 of Perl changed the semantics of C<$[>: files that don't set
1N/Athe value of C<$[> no longer need to worry about whether another
1N/Afile changed its value. (In other words, use of C<$[> is deprecated.)
1N/ASo in general you can assume that
1N/A
1N/A scalar(@whatever) == $#whatever + 1;
1N/A
1N/ASome programmers choose to use an explicit conversion so as to
1N/Aleave nothing to doubt:
1N/A
1N/A $element_count = scalar(@whatever);
1N/A
1N/AIf you evaluate a hash in scalar context, it returns false if the
1N/Ahash is empty. If there are any key/value pairs, it returns true;
1N/Amore precisely, the value returned is a string consisting of the
1N/Anumber of used buckets and the number of allocated buckets, separated
1N/Aby a slash. This is pretty much useful only to find out whether
1N/APerl's internal hashing algorithm is performing poorly on your data
1N/Aset. For example, you stick 10,000 things in a hash, but evaluating
1N/A%HASH in scalar context reveals C<"1/16">, which means only one out
1N/Aof sixteen buckets has been touched, and presumably contains all
1N/A10,000 of your items. This isn't supposed to happen.
1N/A
1N/AYou can preallocate space for a hash by assigning to the keys() function.
1N/AThis rounds up the allocated buckets to the next power of two:
1N/A
1N/A keys(%users) = 1000; # allocate 1024 buckets
1N/A
1N/A=head2 Scalar value constructors
1N/A
1N/ANumeric literals are specified in any of the following floating point or
1N/Ainteger formats:
1N/A
1N/A 12345
1N/A 12345.67
1N/A .23E-10 # a very small number
1N/A 3.14_15_92 # a very important number
1N/A 4_294_967_296 # underscore for legibility
1N/A 0xff # hex
1N/A 0xdead_beef # more hex
1N/A 0377 # octal
1N/A 0b011011 # binary
1N/A
1N/AYou are allowed to use underscores (underbars) in numeric literals
1N/Abetween digits for legibility. You could, for example, group binary
1N/Adigits by threes (as for a Unix-style mode argument such as 0b110_100_100)
1N/Aor by fours (to represent nibbles, as in 0b1010_0110) or in other groups.
1N/A
1N/AString literals are usually delimited by either single or double
1N/Aquotes. They work much like quotes in the standard Unix shells:
1N/Adouble-quoted string literals are subject to backslash and variable
1N/Asubstitution; single-quoted strings are not (except for C<\'> and
1N/AC<\\>). The usual C-style backslash rules apply for making
1N/Acharacters such as newline, tab, etc., as well as some more exotic
1N/Aforms. See L<perlop/"Quote and Quote-like Operators"> for a list.
1N/A
1N/AHexadecimal, octal, or binary, representations in string literals
1N/A(e.g. '0xff') are not automatically converted to their integer
1N/Arepresentation. The hex() and oct() functions make these conversions
1N/Afor you. See L<perlfunc/hex> and L<perlfunc/oct> for more details.
1N/A
1N/AYou can also embed newlines directly in your strings, i.e., they can end
1N/Aon a different line than they begin. This is nice, but if you forget
1N/Ayour trailing quote, the error will not be reported until Perl finds
1N/Aanother line containing the quote character, which may be much further
1N/Aon in the script. Variable substitution inside strings is limited to
1N/Ascalar variables, arrays, and array or hash slices. (In other words,
1N/Anames beginning with $ or @, followed by an optional bracketed
1N/Aexpression as a subscript.) The following code segment prints out "The
1N/Aprice is $Z<>100."
1N/A
1N/A $Price = '$100'; # not interpolated
1N/A print "The price is $Price.\n"; # interpolated
1N/A
1N/AThere is no double interpolation in Perl, so the C<$100> is left as is.
1N/A
1N/AAs in some shells, you can enclose the variable name in braces to
1N/Adisambiguate it from following alphanumerics (and underscores).
1N/AYou must also do
1N/Athis when interpolating a variable into a string to separate the
1N/Avariable name from a following double-colon or an apostrophe, since
1N/Athese would be otherwise treated as a package separator:
1N/A
1N/A $who = "Larry";
1N/A print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";
1N/A print "We use ${who}speak when ${who}'s here.\n";
1N/A
1N/AWithout the braces, Perl would have looked for a $whospeak, a
1N/AC<$who::0>, and a C<$who's> variable. The last two would be the
1N/A$0 and the $s variables in the (presumably) non-existent package
1N/AC<who>.
1N/A
1N/AIn fact, an identifier within such curlies is forced to be a string,
1N/Aas is any simple identifier within a hash subscript. Neither need
1N/Aquoting. Our earlier example, C<$days{'Feb'}> can be written as
1N/AC<$days{Feb}> and the quotes will be assumed automatically. But
1N/Aanything more complicated in the subscript will be interpreted as
1N/Aan expression.
1N/A
1N/A=head3 Version Strings
1N/A
1N/AB<Note:> Version Strings (v-strings) have been deprecated. They will
1N/Anot be available after Perl 5.8. The marginal benefits of v-strings
1N/Awere greatly outweighed by the potential for Surprise and Confusion.
1N/A
1N/AA literal of the form C<v1.20.300.4000> is parsed as a string composed
1N/Aof characters with the specified ordinals. This form, known as
1N/Av-strings, provides an alternative, more readable way to construct
1N/Astrings, rather than use the somewhat less readable interpolation form
1N/AC<"\x{1}\x{14}\x{12c}\x{fa0}">. This is useful for representing
1N/AUnicode strings, and for comparing version "numbers" using the string
1N/Acomparison operators, C<cmp>, C<gt>, C<lt> etc. If there are two or
1N/Amore dots in the literal, the leading C<v> may be omitted.
1N/A
1N/A print v9786; # prints UTF-8 encoded SMILEY, "\x{263a}"
1N/A print v102.111.111; # prints "foo"
1N/A print 102.111.111; # same
1N/A
1N/ASuch literals are accepted by both C<require> and C<use> for
1N/Adoing a version check. The C<$^V> special variable also contains the
1N/Arunning Perl interpreter's version in this form. See L<perlvar/$^V>.
1N/ANote that using the v-strings for IPv4 addresses is not portable unless
1N/Ayou also use the inet_aton()/inet_ntoa() routines of the Socket package.
1N/A
1N/ANote that since Perl 5.8.1 the single-number v-strings (like C<v65>)
1N/Aare not v-strings before the C<< => >> operator (which is usually used
1N/Ato separate a hash key from a hash value), instead they are interpreted
1N/Aas literal strings ('v65'). They were v-strings from Perl 5.6.0 to
1N/APerl 5.8.0, but that caused more confusion and breakage than good.
1N/AMulti-number v-strings like C<v65.66> and C<65.66.67> continue to
1N/Abe v-strings always.
1N/A
1N/A=head3 Special Literals
1N/A
1N/AThe special literals __FILE__, __LINE__, and __PACKAGE__
1N/Arepresent the current filename, line number, and package name at that
1N/Apoint in your program. They may be used only as separate tokens; they
1N/Awill not be interpolated into strings. If there is no current package
1N/A(due to an empty C<package;> directive), __PACKAGE__ is the undefined
1N/Avalue.
1N/A
1N/AThe two control characters ^D and ^Z, and the tokens __END__ and __DATA__
1N/Amay be used to indicate the logical end of the script before the actual
1N/Aend of file. Any following text is ignored.
1N/A
1N/AText after __DATA__ but may be read via the filehandle C<PACKNAME::DATA>,
1N/Awhere C<PACKNAME> is the package that was current when the __DATA__
1N/Atoken was encountered. The filehandle is left open pointing to the
1N/Acontents after __DATA__. It is the program's responsibility to
1N/AC<close DATA> when it is done reading from it. For compatibility with
1N/Aolder scripts written before __DATA__ was introduced, __END__ behaves
1N/Alike __DATA__ in the toplevel script (but not in files loaded with
1N/AC<require> or C<do>) and leaves the remaining contents of the
1N/Afile accessible via C<main::DATA>.
1N/A
1N/ASee L<SelfLoader> for more description of __DATA__, and
1N/Aan example of its use. Note that you cannot read from the DATA
1N/Afilehandle in a BEGIN block: the BEGIN block is executed as soon
1N/Aas it is seen (during compilation), at which point the corresponding
1N/A__DATA__ (or __END__) token has not yet been seen.
1N/A
1N/A=head3 Barewords
1N/A
1N/AA word that has no other interpretation in the grammar will
1N/Abe treated as if it were a quoted string. These are known as
1N/A"barewords". As with filehandles and labels, a bareword that consists
1N/Aentirely of lowercase letters risks conflict with future reserved
1N/Awords, and if you use the C<use warnings> pragma or the B<-w> switch,
1N/APerl will warn you about any
1N/Asuch words. Some people may wish to outlaw barewords entirely. If you
1N/Asay
1N/A
1N/A use strict 'subs';
1N/A
1N/Athen any bareword that would NOT be interpreted as a subroutine call
1N/Aproduces a compile-time error instead. The restriction lasts to the
1N/Aend of the enclosing block. An inner block may countermand this
1N/Aby saying C<no strict 'subs'>.
1N/A
1N/A=head3 Array Joining Delimiter
1N/A
1N/AArrays and slices are interpolated into double-quoted strings
1N/Aby joining the elements with the delimiter specified in the C<$">
1N/Avariable (C<$LIST_SEPARATOR> if "use English;" is specified),
1N/Aspace by default. The following are equivalent:
1N/A
1N/A $temp = join($", @ARGV);
1N/A system "echo $temp";
1N/A
1N/A system "echo @ARGV";
1N/A
1N/AWithin search patterns (which also undergo double-quotish substitution)
1N/Athere is an unfortunate ambiguity: Is C</$foo[bar]/> to be interpreted as
1N/AC</${foo}[bar]/> (where C<[bar]> is a character class for the regular
1N/Aexpression) or as C</${foo[bar]}/> (where C<[bar]> is the subscript to array
1N/A@foo)? If @foo doesn't otherwise exist, then it's obviously a
1N/Acharacter class. If @foo exists, Perl takes a good guess about C<[bar]>,
1N/Aand is almost always right. If it does guess wrong, or if you're just
1N/Aplain paranoid, you can force the correct interpretation with curly
1N/Abraces as above.
1N/A
1N/AIf you're looking for the information on how to use here-documents,
1N/Awhich used to be here, that's been moved to
1N/AL<perlop/Quote and Quote-like Operators>.
1N/A
1N/A=head2 List value constructors
1N/A
1N/AList values are denoted by separating individual values by commas
1N/A(and enclosing the list in parentheses where precedence requires it):
1N/A
1N/A (LIST)
1N/A
1N/AIn a context not requiring a list value, the value of what appears
1N/Ato be a list literal is simply the value of the final element, as
1N/Awith the C comma operator. For example,
1N/A
1N/A @foo = ('cc', '-E', $bar);
1N/A
1N/Aassigns the entire list value to array @foo, but
1N/A
1N/A $foo = ('cc', '-E', $bar);
1N/A
1N/Aassigns the value of variable $bar to the scalar variable $foo.
1N/ANote that the value of an actual array in scalar context is the
1N/Alength of the array; the following assigns the value 3 to $foo:
1N/A
1N/A @foo = ('cc', '-E', $bar);
1N/A $foo = @foo; # $foo gets 3
1N/A
1N/AYou may have an optional comma before the closing parenthesis of a
1N/Alist literal, so that you can say:
1N/A
1N/A @foo = (
1N/A 1,
1N/A 2,
1N/A 3,
1N/A );
1N/A
1N/ATo use a here-document to assign an array, one line per element,
1N/Ayou might use an approach like this:
1N/A
1N/A @sauces = <<End_Lines =~ m/(\S.*\S)/g;
1N/A normal tomato
1N/A spicy tomato
1N/A green chile
1N/A pesto
1N/A white wine
1N/A End_Lines
1N/A
1N/ALISTs do automatic interpolation of sublists. That is, when a LIST is
1N/Aevaluated, each element of the list is evaluated in list context, and
1N/Athe resulting list value is interpolated into LIST just as if each
1N/Aindividual element were a member of LIST. Thus arrays and hashes lose their
1N/Aidentity in a LIST--the list
1N/A
1N/A (@foo,@bar,&SomeSub,%glarch)
1N/A
1N/Acontains all the elements of @foo followed by all the elements of @bar,
1N/Afollowed by all the elements returned by the subroutine named SomeSub
1N/Acalled in list context, followed by the key/value pairs of %glarch.
1N/ATo make a list reference that does I<NOT> interpolate, see L<perlref>.
1N/A
1N/AThe null list is represented by (). Interpolating it in a list
1N/Ahas no effect. Thus ((),(),()) is equivalent to (). Similarly,
1N/Ainterpolating an array with no elements is the same as if no
1N/Aarray had been interpolated at that point.
1N/A
1N/AThis interpolation combines with the facts that the opening
1N/Aand closing parentheses are optional (except when necessary for
1N/Aprecedence) and lists may end with an optional comma to mean that
1N/Amultiple commas within lists are legal syntax. The list C<1,,3> is a
1N/Aconcatenation of two lists, C<1,> and C<3>, the first of which ends
1N/Awith that optional comma. C<1,,3> is C<(1,),(3)> is C<1,3> (And
1N/Asimilarly for C<1,,,3> is C<(1,),(,),3> is C<1,3> and so on.) Not that
1N/Awe'd advise you to use this obfuscation.
1N/A
1N/AA list value may also be subscripted like a normal array. You must
1N/Aput the list in parentheses to avoid ambiguity. For example:
1N/A
1N/A # Stat returns list value.
1N/A $time = (stat($file))[8];
1N/A
1N/A # SYNTAX ERROR HERE.
1N/A $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES
1N/A
1N/A # Find a hex digit.
1N/A $hexdigit = ('a','b','c','d','e','f')[$digit-10];
1N/A
1N/A # A "reverse comma operator".
1N/A return (pop(@foo),pop(@foo))[0];
1N/A
1N/ALists may be assigned to only when each element of the list
1N/Ais itself legal to assign to:
1N/A
1N/A ($a, $b, $c) = (1, 2, 3);
1N/A
1N/A ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
1N/A
1N/AAn exception to this is that you may assign to C<undef> in a list.
1N/AThis is useful for throwing away some of the return values of a
1N/Afunction:
1N/A
1N/A ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
1N/A
1N/AList assignment in scalar context returns the number of elements
1N/Aproduced by the expression on the right side of the assignment:
1N/A
1N/A $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
1N/A $x = (($foo,$bar) = f()); # set $x to f()'s return count
1N/A
1N/AThis is handy when you want to do a list assignment in a Boolean
1N/Acontext, because most list functions return a null list when finished,
1N/Awhich when assigned produces a 0, which is interpreted as FALSE.
1N/A
1N/AIt's also the source of a useful idiom for executing a function or
1N/Aperforming an operation in list context and then counting the number of
1N/Areturn values, by assigning to an empty list and then using that
1N/Aassignment in scalar context. For example, this code:
1N/A
1N/A $count = () = $string =~ /\d+/g;
1N/A
1N/Awill place into $count the number of digit groups found in $string.
1N/AThis happens because the pattern match is in list context (since it
1N/Ais being assigned to the empty list), and will therefore return a list
1N/Aof all matching parts of the string. The list assignment in scalar
1N/Acontext will translate that into the number of elements (here, the
1N/Anumber of times the pattern matched) and assign that to $count. Note
1N/Athat simply using
1N/A
1N/A $count = $string =~ /\d+/g;
1N/A
1N/Awould not have worked, since a pattern match in scalar context will
1N/Aonly return true or false, rather than a count of matches.
1N/A
1N/AThe final element of a list assignment may be an array or a hash:
1N/A
1N/A ($a, $b, @rest) = split;
1N/A my($a, $b, %rest) = @_;
1N/A
1N/AYou can actually put an array or hash anywhere in the list, but the first one
1N/Ain the list will soak up all the values, and anything after it will become
1N/Aundefined. This may be useful in a my() or local().
1N/A
1N/AA hash can be initialized using a literal list holding pairs of
1N/Aitems to be interpreted as a key and a value:
1N/A
1N/A # same as map assignment above
1N/A %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
1N/A
1N/AWhile literal lists and named arrays are often interchangeable, that's
1N/Anot the case for hashes. Just because you can subscript a list value like
1N/Aa normal array does not mean that you can subscript a list value as a
1N/Ahash. Likewise, hashes included as parts of other lists (including
1N/Aparameters lists and return lists from functions) always flatten out into
1N/Akey/value pairs. That's why it's good to use references sometimes.
1N/A
1N/AIt is often more readable to use the C<< => >> operator between key/value
1N/Apairs. The C<< => >> operator is mostly just a more visually distinctive
1N/Asynonym for a comma, but it also arranges for its left-hand operand to be
1N/Ainterpreted as a string -- if it's a bareword that would be a legal simple
1N/Aidentifier (C<< => >> doesn't quote compound identifiers, that contain
1N/Adouble colons). This makes it nice for initializing hashes:
1N/A
1N/A %map = (
1N/A red => 0x00f,
1N/A blue => 0x0f0,
1N/A green => 0xf00,
1N/A );
1N/A
1N/Aor for initializing hash references to be used as records:
1N/A
1N/A $rec = {
1N/A witch => 'Mable the Merciless',
1N/A cat => 'Fluffy the Ferocious',
1N/A date => '10/31/1776',
1N/A };
1N/A
1N/Aor for using call-by-named-parameter to complicated functions:
1N/A
1N/A $field = $query->radio_group(
1N/A name => 'group_name',
1N/A values => ['eenie','meenie','minie'],
1N/A default => 'meenie',
1N/A linebreak => 'true',
1N/A labels => \%labels
1N/A );
1N/A
1N/ANote that just because a hash is initialized in that order doesn't
1N/Amean that it comes out in that order. See L<perlfunc/sort> for examples
1N/Aof how to arrange for an output ordering.
1N/A
1N/A=head2 Subscripts
1N/A
1N/AAn array is subscripted by specifying a dollary sign (C<$>), then the
1N/Aname of the array (without the leading C<@>), then the subscript inside
1N/Asquare brackets. For example:
1N/A
1N/A @myarray = (5, 50, 500, 5000);
1N/A print "Element Number 2 is", $myarray[2], "\n";
1N/A
1N/AThe array indices start with 0. A negative subscript retrieves its
1N/Avalue from the end. In our example, C<$myarray[-1]> would have been
1N/A5000, and C<$myarray[-2]> would have been 500.
1N/A
1N/AHash subscripts are similar, only instead of square brackets curly brackets
1N/Aare used. For example:
1N/A
1N/A %scientists =
1N/A (
1N/A "Newton" => "Isaac",
1N/A "Einstein" => "Albert",
1N/A "Darwin" => "Charles",
1N/A "Feynman" => "Richard",
1N/A );
1N/A
1N/A print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";
1N/A
1N/A=head2 Slices
1N/A
1N/AA common way to access an array or a hash is one scalar element at a
1N/Atime. You can also subscript a list to get a single element from it.
1N/A
1N/A $whoami = $ENV{"USER"}; # one element from the hash
1N/A $parent = $ISA[0]; # one element from the array
1N/A $dir = (getpwnam("daemon"))[7]; # likewise, but with list
1N/A
1N/AA slice accesses several elements of a list, an array, or a hash
1N/Asimultaneously using a list of subscripts. It's more convenient
1N/Athan writing out the individual elements as a list of separate
1N/Ascalar values.
1N/A
1N/A ($him, $her) = @folks[0,-1]; # array slice
1N/A @them = @folks[0 .. 3]; # array slice
1N/A ($who, $home) = @ENV{"USER", "HOME"}; # hash slice
1N/A ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice
1N/A
1N/ASince you can assign to a list of variables, you can also assign to
1N/Aan array or hash slice.
1N/A
1N/A @days[3..5] = qw/Wed Thu Fri/;
1N/A @colors{'red','blue','green'}
1N/A = (0xff0000, 0x0000ff, 0x00ff00);
1N/A @folks[0, -1] = @folks[-1, 0];
1N/A
1N/AThe previous assignments are exactly equivalent to
1N/A
1N/A ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
1N/A ($colors{'red'}, $colors{'blue'}, $colors{'green'})
1N/A = (0xff0000, 0x0000ff, 0x00ff00);
1N/A ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);
1N/A
1N/ASince changing a slice changes the original array or hash that it's
1N/Aslicing, a C<foreach> construct will alter some--or even all--of the
1N/Avalues of the array or hash.
1N/A
1N/A foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }
1N/A
1N/A foreach (@hash{qw[key1 key2]}) {
1N/A s/^\s+//; # trim leading whitespace
1N/A s/\s+$//; # trim trailing whitespace
1N/A s/(\w+)/\u\L$1/g; # "titlecase" words
1N/A }
1N/A
1N/AA slice of an empty list is still an empty list. Thus:
1N/A
1N/A @a = ()[1,0]; # @a has no elements
1N/A @b = (@a)[0,1]; # @b has no elements
1N/A @c = (0,1)[2,3]; # @c has no elements
1N/A
1N/ABut:
1N/A
1N/A @a = (1)[1,0]; # @a has two elements
1N/A @b = (1,undef)[1,0,2]; # @b has three elements
1N/A
1N/AThis makes it easy to write loops that terminate when a null list
1N/Ais returned:
1N/A
1N/A while ( ($home, $user) = (getpwent)[7,0]) {
1N/A printf "%-8s %s\n", $user, $home;
1N/A }
1N/A
1N/AAs noted earlier in this document, the scalar sense of list assignment
1N/Ais the number of elements on the right-hand side of the assignment.
1N/AThe null list contains no elements, so when the password file is
1N/Aexhausted, the result is 0, not 2.
1N/A
1N/AIf you're confused about why you use an '@' there on a hash slice
1N/Ainstead of a '%', think of it like this. The type of bracket (square
1N/Aor curly) governs whether it's an array or a hash being looked at.
1N/AOn the other hand, the leading symbol ('$' or '@') on the array or
1N/Ahash indicates whether you are getting back a singular value (a
1N/Ascalar) or a plural one (a list).
1N/A
1N/A=head2 Typeglobs and Filehandles
1N/A
1N/APerl uses an internal type called a I<typeglob> to hold an entire
1N/Asymbol table entry. The type prefix of a typeglob is a C<*>, because
1N/Ait represents all types. This used to be the preferred way to
1N/Apass arrays and hashes by reference into a function, but now that
1N/Awe have real references, this is seldom needed.
1N/A
1N/AThe main use of typeglobs in modern Perl is create symbol table aliases.
1N/AThis assignment:
1N/A
1N/A *this = *that;
1N/A
1N/Amakes $this an alias for $that, @this an alias for @that, %this an alias
1N/Afor %that, &this an alias for &that, etc. Much safer is to use a reference.
1N/AThis:
1N/A
1N/A local *Here::blue = \$There::green;
1N/A
1N/Atemporarily makes $Here::blue an alias for $There::green, but doesn't
1N/Amake @Here::blue an alias for @There::green, or %Here::blue an alias for
1N/A%There::green, etc. See L<perlmod/"Symbol Tables"> for more examples
1N/Aof this. Strange though this may seem, this is the basis for the whole
1N/Amodule import/export system.
1N/A
1N/AAnother use for typeglobs is to pass filehandles into a function or
1N/Ato create new filehandles. If you need to use a typeglob to save away
1N/Aa filehandle, do it this way:
1N/A
1N/A $fh = *STDOUT;
1N/A
1N/Aor perhaps as a real reference, like this:
1N/A
1N/A $fh = \*STDOUT;
1N/A
1N/ASee L<perlsub> for examples of using these as indirect filehandles
1N/Ain functions.
1N/A
1N/ATypeglobs are also a way to create a local filehandle using the local()
1N/Aoperator. These last until their block is exited, but may be passed back.
1N/AFor example:
1N/A
1N/A sub newopen {
1N/A my $path = shift;
1N/A local *FH; # not my!
1N/A open (FH, $path) or return undef;
1N/A return *FH;
1N/A }
1N/A $fh = newopen('/etc/passwd');
1N/A
1N/ANow that we have the C<*foo{THING}> notation, typeglobs aren't used as much
1N/Afor filehandle manipulations, although they're still needed to pass brand
1N/Anew file and directory handles into or out of functions. That's because
1N/AC<*HANDLE{IO}> only works if HANDLE has already been used as a handle.
1N/AIn other words, C<*FH> must be used to create new symbol table entries;
1N/AC<*foo{THING}> cannot. When in doubt, use C<*FH>.
1N/A
1N/AAll functions that are capable of creating filehandles (open(),
1N/Aopendir(), pipe(), socketpair(), sysopen(), socket(), and accept())
1N/Aautomatically create an anonymous filehandle if the handle passed to
1N/Athem is an uninitialized scalar variable. This allows the constructs
1N/Asuch as C<open(my $fh, ...)> and C<open(local $fh,...)> to be used to
1N/Acreate filehandles that will conveniently be closed automatically when
1N/Athe scope ends, provided there are no other references to them. This
1N/Alargely eliminates the need for typeglobs when opening filehandles
1N/Athat must be passed around, as in the following example:
1N/A
1N/A sub myopen {
1N/A open my $fh, "@_"
1N/A or die "Can't open '@_': $!";
1N/A return $fh;
1N/A }
1N/A
1N/A {
1N/A my $f = myopen("</etc/motd");
1N/A print <$f>;
1N/A # $f implicitly closed here
1N/A }
1N/A
1N/ANote that if an initialized scalar variable is used instead the
1N/Aresult is different: C<my $fh='zzz'; open($fh, ...)> is equivalent
1N/Ato C<open( *{'zzz'}, ...)>.
1N/AC<use strict 'refs'> forbids such practice.
1N/A
1N/AAnother way to create anonymous filehandles is with the Symbol
1N/Amodule or with the IO::Handle module and its ilk. These modules
1N/Ahave the advantage of not hiding different types of the same name
1N/Aduring the local(). See the bottom of L<perlfunc/open()> for an
1N/Aexample.
1N/A
1N/A=head1 SEE ALSO
1N/A
1N/ASee L<perlvar> for a description of Perl's built-in variables and
1N/Aa discussion of legal variable names. See L<perlref>, L<perlsub>,
1N/Aand L<perlmod/"Symbol Tables"> for more discussion on typeglobs and
1N/Athe C<*foo{THING}> syntax.