home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 10 / AU_CD10.iso / Updates / Perl / Non-RPC / Docs / perldata < prev    next >
Text File  |  1999-04-17  |  27KB  |  680 lines

  1. NAME
  2.     perldata - Perl data types
  3.  
  4. DESCRIPTION
  5.   Variable names
  6.  
  7.     Perl has three data structures: scalars, arrays of scalars, and
  8.     associative arrays of scalars, known as "hashes". Normal arrays
  9.     are indexed by number, starting with 0. (Negative subscripts
  10.     count from the end.) Hash arrays are indexed by string.
  11.  
  12.     Values are usually referred to by name (or through a named
  13.     reference). The first character of the name tells you to what
  14.     sort of data structure it refers. The rest of the name tells you
  15.     the particular value to which it refers. Most often, it consists
  16.     of a single *identifier*, that is, a string beginning with a
  17.     letter or underscore, and containing letters, underscores, and
  18.     digits. In some cases, it may be a chain of identifiers,
  19.     separated by `::' (or by `'', but that's deprecated); all but
  20.     the last are interpreted as names of packages, to locate the
  21.     namespace in which to look up the final identifier (see the
  22.     "Packages" entry in the perlmod manpage for details). It's
  23.     possible to substitute for a simple identifier an expression
  24.     that produces a reference to the value at runtime; this is
  25.     described in more detail below, and in the perlref manpage.
  26.  
  27.     There are also special variables whose names don't follow these
  28.     rules, so that they don't accidentally collide with one of your
  29.     normal variables. Strings that match parenthesized parts of a
  30.     regular expression are saved under names containing only digits
  31.     after the `$' (see the perlop manpage and the perlre manpage).
  32.     In addition, several special variables that provide windows into
  33.     the inner working of Perl have names containing punctuation
  34.     characters (see the perlvar manpage).
  35.  
  36.     Scalar values are always named with '$', even when referring to
  37.     a scalar that is part of an array. It works like the English
  38.     word "the". Thus we have:
  39.  
  40.         $days        # the simple scalar value "days"
  41.         $days[28]        # the 29th element of array @days
  42.         $days{'Feb'}    # the 'Feb' value from hash %days
  43.         $#days        # the last index of array @days
  44.  
  45.  
  46.     but entire arrays or array slices are denoted by '@', which
  47.     works much like the word "these" or "those":
  48.  
  49.         @days        # ($days[0], $days[1],... $days[n])
  50.         @days[3,4,5]    # same as @days[3..5]
  51.         @days{'a','c'}    # same as ($days{'a'},$days{'c'})
  52.  
  53.  
  54.     and entire hashes are denoted by '%':
  55.  
  56.         %days        # (key1, val1, key2, val2 ...)
  57.  
  58.  
  59.     In addition, subroutines are named with an initial '&', though
  60.     this is optional when it's otherwise unambiguous (just as "do"
  61.     is often redundant in English). Symbol table entries can be
  62.     named with an initial '*', but you don't really care about that
  63.     yet.
  64.  
  65.     Every variable type has its own namespace. You can, without fear
  66.     of conflict, use the same name for a scalar variable, an array,
  67.     or a hash (or, for that matter, a filehandle, a subroutine name,
  68.     or a label). This means that $foo and @foo are two different
  69.     variables. It also means that `$foo[1]' is a part of @foo, not a
  70.     part of $foo. This may seem a bit weird, but that's okay,
  71.     because it is weird.
  72.  
  73.     Because variable and array references always start with '$',
  74.     '@', or '%', the "reserved" words aren't in fact reserved with
  75.     respect to variable names. (They ARE reserved with respect to
  76.     labels and filehandles, however, which don't have an initial
  77.     special character. You can't have a filehandle named "log", for
  78.     instance. Hint: you could say `open(LOG,'logfile')' rather than
  79.     `open(log,'logfile')'. Using uppercase filehandles also improves
  80.     readability and protects you from conflict with future reserved
  81.     words.) Case *IS* significant--"FOO", "Foo", and "foo" are all
  82.     different names. Names that start with a letter or underscore
  83.     may also contain digits and underscores.
  84.  
  85.     It is possible to replace such an alphanumeric name with an
  86.     expression that returns a reference to an object of that type.
  87.     For a description of this, see the perlref manpage.
  88.  
  89.     Names that start with a digit may contain only more digits.
  90.     Names that do not start with a letter, underscore, or digit are
  91.     limited to one character, e.g., `$%' or `$$'. (Most of these one
  92.     character names have a predefined significance to Perl. For
  93.     instance, `$$' is the current process id.)
  94.  
  95.   Context
  96.  
  97.     The interpretation of operations and values in Perl sometimes
  98.     depends on the requirements of the context around the operation
  99.     or value. There are two major contexts: scalar and list. Certain
  100.     operations return list values in contexts wanting a list, and
  101.     scalar values otherwise. (If this is true of an operation it
  102.     will be mentioned in the documentation for that operation.) In
  103.     other words, Perl overloads certain operations based on whether
  104.     the expected return value is singular or plural. (Some words in
  105.     English work this way, like "fish" and "sheep".)
  106.  
  107.     In a reciprocal fashion, an operation provides either a scalar
  108.     or a list context to each of its arguments. For example, if you
  109.     say
  110.  
  111.         int( <STDIN> )
  112.  
  113.  
  114.     the integer operation provides a scalar context for the <STDIN>
  115.     operator, which responds by reading one line from STDIN and
  116.     passing it back to the integer operation, which will then find
  117.     the integer value of that line and return that. If, on the other
  118.     hand, you say
  119.  
  120.         sort( <STDIN> )
  121.  
  122.  
  123.     then the sort operation provides a list context for <STDIN>,
  124.     which will proceed to read every line available up to the end of
  125.     file, and pass that list of lines back to the sort routine,
  126.     which will then sort those lines and return them as a list to
  127.     whatever the context of the sort was.
  128.  
  129.     Assignment is a little bit special in that it uses its left
  130.     argument to determine the context for the right argument.
  131.     Assignment to a scalar evaluates the righthand side in a scalar
  132.     context, while assignment to an array or array slice evaluates
  133.     the righthand side in a list context. Assignment to a list also
  134.     evaluates the righthand side in a list context.
  135.  
  136.     User defined subroutines may choose to care whether they are
  137.     being called in a scalar or list context, but most subroutines
  138.     do not need to care, because scalars are automatically
  139.     interpolated into lists. See the "wantarray" entry in the
  140.     perlfunc manpage.
  141.  
  142.   Scalar values
  143.  
  144.     All data in Perl is a scalar or an array of scalars or a hash of
  145.     scalars. Scalar variables may contain various kinds of singular
  146.     data, such as numbers, strings, and references. In general,
  147.     conversion from one form to another is transparent. (A scalar
  148.     may not contain multiple values, but may contain a reference to
  149.     an array or hash containing multiple values.) Because of the
  150.     automatic conversion of scalars, operations, and functions that
  151.     return scalars don't need to care (and, in fact, can't care)
  152.     whether the context is looking for a string or a number.
  153.  
  154.     Scalars aren't necessarily one thing or another. There's no
  155.     place to declare a scalar variable to be of type "string", or of
  156.     type "number", or type "filehandle", or anything else. Perl is a
  157.     contextually polymorphic language whose scalars can be strings,
  158.     numbers, or references (which includes objects). While strings
  159.     and numbers are considered pretty much the same thing for nearly
  160.     all purposes, references are strongly-typed uncastable pointers
  161.     with builtin reference-counting and destructor invocation.
  162.  
  163.     A scalar value is interpreted as TRUE in the Boolean sense if it
  164.     is not the null string or the number 0 (or its string
  165.     equivalent, "0"). The Boolean context is just a special kind of
  166.     scalar context.
  167.  
  168.     There are actually two varieties of null scalars: defined and
  169.     undefined. Undefined null scalars are returned when there is no
  170.     real value for something, such as when there was an error, or at
  171.     end of file, or when you refer to an uninitialized variable or
  172.     element of an array. An undefined null scalar may become defined
  173.     the first time you use it as if it were defined, but prior to
  174.     that you can use the defined() operator to determine whether the
  175.     value is defined or not.
  176.  
  177.     To find out whether a given string is a valid nonzero number,
  178.     it's usually enough to test it against both numeric 0 and also
  179.     lexical "0" (although this will cause -w noises). That's because
  180.     strings that aren't numbers count as 0, just as they do in awk:
  181.  
  182.         if ($str == 0 && $str ne "0")  {
  183.         warn "That doesn't look like a number";
  184.         }
  185.  
  186.  
  187.     That's usually preferable because otherwise you won't treat IEEE
  188.     notations like `NaN' or `Infinity' properly. At other times you
  189.     might prefer to use the POSIX::strtod function or a regular
  190.     expression to check whether data is numeric. See the perlre
  191.     manpage for details on regular expressions.
  192.  
  193.         warn "has nondigits"    if     /\D/;
  194.         warn "not a natural number" unless /^\d+$/;             # rejects -3
  195.         warn "not an integer"       unless /^-?\d+$/;           # rejects +3
  196.         warn "not an integer"       unless /^[+-]?\d+$/;
  197.         warn "not a decimal number" unless /^-?\d+\.?\d*$/;     # rejects .2
  198.         warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
  199.         warn "not a C float"
  200.         unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
  201.  
  202.  
  203.     The length of an array is a scalar value. You may find the
  204.     length of array @days by evaluating `$#days', as in csh.
  205.     (Actually, it's not the length of the array, it's the subscript
  206.     of the last element, because there is (ordinarily) a 0th
  207.     element.) Assigning to `$#days' changes the length of the array.
  208.     Shortening an array by this method destroys intervening values.
  209.     Lengthening an array that was previously shortened *NO LONGER*
  210.     recovers the values that were in those elements. (It used to in
  211.     Perl 4, but we had to break this to make sure destructors were
  212.     called when expected.) You can also gain some miniscule measure
  213.     of efficiency by pre-extending an array that is going to get
  214.     big. (You can also extend an array by assigning to an element
  215.     that is off the end of the array.) You can truncate an array
  216.     down to nothing by assigning the null list () to it. The
  217.     following are equivalent:
  218.  
  219.         @whatever = ();
  220.         $#whatever = -1;
  221.  
  222.  
  223.     If you evaluate a named array in a scalar context, it returns
  224.     the length of the array. (Note that this is not true of lists,
  225.     which return the last value, like the C comma operator, nor of
  226.     built-in functions, which return whatever they feel like
  227.     returning.) The following is always true:
  228.  
  229.         scalar(@whatever) == $#whatever - $[ + 1;
  230.  
  231.  
  232.     Version 5 of Perl changed the semantics of `$[': files that
  233.     don't set the value of `$[' no longer need to worry about
  234.     whether another file changed its value. (In other words, use of
  235.     `$[' is deprecated.) So in general you can assume that
  236.  
  237.         scalar(@whatever) == $#whatever + 1;
  238.  
  239.  
  240.     Some programmers choose to use an explicit conversion so
  241.     nothing's left to doubt:
  242.  
  243.         $element_count = scalar(@whatever);
  244.  
  245.  
  246.     If you evaluate a hash in a scalar context, it returns a value
  247.     that is true if and only if the hash contains any key/value
  248.     pairs. (If there are any key/value pairs, the value returned is
  249.     a string consisting of the number of used buckets and the number
  250.     of allocated buckets, separated by a slash. This is pretty much
  251.     useful only to find out whether Perl's (compiled in) hashing
  252.     algorithm is performing poorly on your data set. For example,
  253.     you stick 10,000 things in a hash, but evaluating %HASH in
  254.     scalar context reveals "1/16", which means only one out of
  255.     sixteen buckets has been touched, and presumably contains all
  256.     10,000 of your items. This isn't supposed to happen.)
  257.  
  258.     You can preallocate space for a hash by assigning to the keys()
  259.     function. This rounds up the allocated bucked to the next power
  260.     of two:
  261.  
  262.         keys(%users) = 1000;        # allocate 1024 buckets
  263.  
  264.  
  265.   Scalar value constructors
  266.  
  267.     Numeric literals are specified in any of the customary floating
  268.     point or integer formats:
  269.  
  270.         12345
  271.         12345.67
  272.         .23E-10
  273.         0xffff        # hex
  274.         0377        # octal
  275.         4_294_967_296    # underline for legibility
  276.  
  277.  
  278.     String literals are usually delimited by either single or double
  279.     quotes. They work much like shell quotes: double-quoted string
  280.     literals are subject to backslash and variable substitution;
  281.     single-quoted strings are not (except for "`\''" and "`\\'").
  282.     The usual Unix backslash rules apply for making characters such
  283.     as newline, tab, etc., as well as some more exotic forms. See
  284.     the section on "Quote and Quotelike Operators" in the perlop
  285.     manpage for a list.
  286.  
  287.     Octal or hex representations in string literals (e.g. '0xffff')
  288.     are not automatically converted to their integer representation.
  289.     The hex() and oct() functions make these conversions for you.
  290.     See the "hex" entry in the perlfunc manpage and the "oct" entry
  291.     in the perlfunc manpage for more details.
  292.  
  293.     You can also embed newlines directly in your strings, i.e., they
  294.     can end on a different line than they begin. This is nice, but
  295.     if you forget your trailing quote, the error will not be
  296.     reported until Perl finds another line containing the quote
  297.     character, which may be much further on in the script. Variable
  298.     substitution inside strings is limited to scalar variables,
  299.     arrays, and array slices. (In other words, names beginning with
  300.     $ or @, followed by an optional bracketed expression as a
  301.     subscript.) The following code segment prints out "The price is
  302.     $100."
  303.  
  304.         $Price = '$100';    # not interpreted
  305.         print "The price is $Price.\n";    # interpreted
  306.  
  307.  
  308.     As in some shells, you can put curly brackets around the name to
  309.     delimit it from following alphanumerics. In fact, an identifier
  310.     within such curlies is forced to be a string, as is any single
  311.     identifier within a hash subscript. Our earlier example,
  312.  
  313.         $days{'Feb'}
  314.  
  315.  
  316.     can be written as
  317.  
  318.         $days{Feb}
  319.  
  320.  
  321.     and the quotes will be assumed automatically. But anything more
  322.     complicated in the subscript will be interpreted as an
  323.     expression.
  324.  
  325.     Note that a single-quoted string must be separated from a
  326.     preceding word by a space, because single quote is a valid
  327.     (though deprecated) character in a variable name (see the
  328.     "Packages" entry in the perlmod manpage).
  329.  
  330.     Three special literals are __FILE__, __LINE__, and __PACKAGE__,
  331.     which represent the current filename, line number, and package
  332.     name at that point in your program. They may be used only as
  333.     separate tokens; they will not be interpolated into strings. If
  334.     there is no current package (due to an empty `package;'
  335.     directive), __PACKAGE__ is the undefined value.
  336.  
  337.     The tokens __END__ and __DATA__ may be used to indicate the
  338.     logical end of the script before the actual end of file. Any
  339.     following text is ignored, but may be read via a DATA
  340.     filehandle: main::DATA for __END__, or PACKNAME::DATA (where
  341.     PACKNAME is the current package) for __DATA__. The two control
  342.     characters ^D and ^Z are synonyms for __END__ (or __DATA__ in a
  343.     module). See the SelfLoader manpage for more description of
  344.     __DATA__, and an example of its use. Note that you cannot read
  345.     from the DATA filehandle in a BEGIN block: the BEGIN block is
  346.     executed as soon as it is seen (during compilation), at which
  347.     point the corresponding __DATA__ (or __END__) token has not yet
  348.     been seen.
  349.  
  350.     A word that has no other interpretation in the grammar will be
  351.     treated as if it were a quoted string. These are known as
  352.     "barewords". As with filehandles and labels, a bareword that
  353.     consists entirely of lowercase letters risks conflict with
  354.     future reserved words, and if you use the -w switch, Perl will
  355.     warn you about any such words. Some people may wish to outlaw
  356.     barewords entirely. If you say
  357.  
  358.         use strict 'subs';
  359.  
  360.  
  361.     then any bareword that would NOT be interpreted as a subroutine
  362.     call produces a compile-time error instead. The restriction
  363.     lasts to the end of the enclosing block. An inner block may
  364.     countermand this by saying `no strict 'subs''.
  365.  
  366.     Array variables are interpolated into double-quoted strings by
  367.     joining all the elements of the array with the delimiter
  368.     specified in the `$"' variable (`$LIST_SEPARATOR' in English),
  369.     space by default. The following are equivalent:
  370.  
  371.         $temp = join($",@ARGV);
  372.         system "echo $temp";
  373.  
  374.         system "echo @ARGV";
  375.  
  376.  
  377.     Within search patterns (which also undergo double-quotish
  378.     substitution) there is a bad ambiguity: Is `/$foo[bar]/' to be
  379.     interpreted as `/${foo}[bar]/' (where `[bar]' is a character
  380.     class for the regular expression) or as `/${foo[bar]}/' (where
  381.     `[bar]' is the subscript to array @foo)? If @foo doesn't
  382.     otherwise exist, then it's obviously a character class. If @foo
  383.     exists, Perl takes a good guess about `[bar]', and is almost
  384.     always right. If it does guess wrong, or if you're just plain
  385.     paranoid, you can force the correct interpretation with curly
  386.     brackets as above.
  387.  
  388.     A line-oriented form of quoting is based on the shell "here-doc"
  389.     syntax. Following a `<<' you specify a string to terminate the
  390.     quoted material, and all lines following the current line down
  391.     to the terminating string are the value of the item. The
  392.     terminating string may be either an identifier (a word), or some
  393.     quoted text. If quoted, the type of quotes you use determines
  394.     the treatment of the text, just as in regular quoting. An
  395.     unquoted identifier works like double quotes. There must be no
  396.     space between the `<<' and the identifier. (If you put a space
  397.     it will be treated as a null identifier, which is valid, and
  398.     matches the first empty line.) The terminating string must
  399.     appear by itself (unquoted and with no surrounding whitespace)
  400.     on the terminating line.
  401.  
  402.         print <<EOF;
  403.         The price is $Price.
  404.         EOF
  405.  
  406.         print <<"EOF";    # same as above
  407.         The price is $Price.
  408.         EOF
  409.  
  410.         print <<`EOC`;    # execute commands
  411.         echo hi there
  412.         echo lo there
  413.         EOC
  414.  
  415.         print <<"foo", <<"bar";    # you can stack them
  416.         I said foo.
  417.         foo
  418.         I said bar.
  419.         bar
  420.  
  421.         myfunc(<<"THIS", 23, <<'THAT');
  422.         Here's a line
  423.         or two.
  424.         THIS
  425.         and here's another.
  426.         THAT
  427.  
  428.  
  429.     Just don't forget that you have to put a semicolon on the end to
  430.     finish the statement, as Perl doesn't know you're not going to
  431.     try to do this:
  432.  
  433.         print <<ABC
  434.         179231
  435.         ABC
  436.         + 20;
  437.  
  438.  
  439.   List value constructors
  440.  
  441.     List values are denoted by separating individual values by
  442.     commas (and enclosing the list in parentheses where precedence
  443.     requires it):
  444.  
  445.         (LIST)
  446.  
  447.  
  448.     In a context not requiring a list value, the value of the list
  449.     literal is the value of the final element, as with the C comma
  450.     operator. For example,
  451.  
  452.         @foo = ('cc', '-E', $bar);
  453.  
  454.  
  455.     assigns the entire list value to array foo, but
  456.  
  457.         $foo = ('cc', '-E', $bar);
  458.  
  459.  
  460.     assigns the value of variable bar to variable foo. Note that the
  461.     value of an actual array in a scalar context is the length of
  462.     the array; the following assigns the value 3 to $foo:
  463.  
  464.         @foo = ('cc', '-E', $bar);
  465.         $foo = @foo;        # $foo gets 3
  466.  
  467.  
  468.     You may have an optional comma before the closing parenthesis of
  469.     a list literal, so that you can say:
  470.  
  471.         @foo = (
  472.         1,
  473.         2,
  474.         3,
  475.         );
  476.  
  477.  
  478.     LISTs do automatic interpolation of sublists. That is, when a
  479.     LIST is evaluated, each element of the list is evaluated in a
  480.     list context, and the resulting list value is interpolated into
  481.     LIST just as if each individual element were a member of LIST.
  482.     Thus arrays and hashes lose their identity in a LIST--the list
  483.  
  484.         (@foo,@bar,&SomeSub,%glarch)
  485.  
  486.  
  487.     contains all the elements of @foo followed by all the elements
  488.     of @bar, followed by all the elements returned by the subroutine
  489.     named SomeSub called in a list context, followed by the
  490.     key/value pairs of %glarch. To make a list reference that does
  491.     *NOT* interpolate, see the perlref manpage.
  492.  
  493.     The null list is represented by (). Interpolating it in a list
  494.     has no effect. Thus ((),(),()) is equivalent to (). Similarly,
  495.     interpolating an array with no elements is the same as if no
  496.     array had been interpolated at that point.
  497.  
  498.     A list value may also be subscripted like a normal array. You
  499.     must put the list in parentheses to avoid ambiguity. For
  500.     example:
  501.  
  502.         # Stat returns list value.
  503.         $time = (stat($file))[8];
  504.  
  505.         # SYNTAX ERROR HERE.
  506.         $time = stat($file)[8];  # OOPS, FORGOT PARENTHESES
  507.  
  508.         # Find a hex digit.
  509.         $hexdigit = ('a','b','c','d','e','f')[$digit-10];
  510.  
  511.         # A "reverse comma operator".
  512.         return (pop(@foo),pop(@foo))[0];
  513.  
  514.  
  515.     You may assign to `undef' in a list. This is useful for throwing
  516.     away some of the return values of a function:
  517.  
  518.         ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
  519.  
  520.  
  521.     Lists may be assigned to if and only if each element of the list
  522.     is legal to assign to:
  523.  
  524.         ($a, $b, $c) = (1, 2, 3);
  525.  
  526.         ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  527.  
  528.  
  529.     List assignment in a scalar context returns the number of
  530.     elements produced by the expression on the right side of the
  531.     assignment:
  532.  
  533.         $x = (($foo,$bar) = (3,2,1));    # set $x to 3, not 2
  534.         $x = (($foo,$bar) = f());            # set $x to f()'s return count
  535.  
  536.  
  537.     This is very handy when you want to do a list assignment in a
  538.     Boolean context, because most list functions return a null list
  539.     when finished, which when assigned produces a 0, which is
  540.     interpreted as FALSE.
  541.  
  542.     The final element may be an array or a hash:
  543.  
  544.         ($a, $b, @rest) = split;
  545.         my($a, $b, %rest) = @_;
  546.  
  547.  
  548.     You can actually put an array or hash anywhere in the list, but
  549.     the first one in the list will soak up all the values, and
  550.     anything after it will get a null value. This may be useful in a
  551.     local() or my().
  552.  
  553.     A hash literal contains pairs of values to be interpreted as a
  554.     key and a value:
  555.  
  556.         # same as map assignment above
  557.         %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  558.  
  559.  
  560.     While literal lists and named arrays are usually
  561.     interchangeable, that's not the case for hashes. Just because
  562.     you can subscript a list value like a normal array does not mean
  563.     that you can subscript a list value as a hash. Likewise, hashes
  564.     included as parts of other lists (including parameters lists and
  565.     return lists from functions) always flatten out into key/value
  566.     pairs. That's why it's good to use references sometimes.
  567.  
  568.     It is often more readable to use the `=>' operator between
  569.     key/value pairs. The `=>' operator is mostly just a more
  570.     visually distinctive synonym for a comma, but it also arranges
  571.     for its left-hand operand to be interpreted as a string--if it's
  572.     a bareword that would be a legal identifier. This makes it nice
  573.     for initializing hashes:
  574.  
  575.         %map = (
  576.              red   => 0x00f,
  577.              blue  => 0x0f0,
  578.              green => 0xf00,
  579.        );
  580.  
  581.  
  582.     or for initializing hash references to be used as records:
  583.  
  584.         $rec = {
  585.             witch => 'Mable the Merciless',
  586.             cat   => 'Fluffy the Ferocious',
  587.             date  => '10/31/1776',
  588.         };
  589.  
  590.  
  591.     or for using call-by-named-parameter to complicated functions:
  592.  
  593.        $field = $query->radio_group(
  594.                name      => 'group_name',
  595.                    values    => ['eenie','meenie','minie'],
  596.                    default   => 'meenie',
  597.                    linebreak => 'true',
  598.                    labels    => \%labels
  599.        );
  600.  
  601.  
  602.     Note that just because a hash is initialized in that order
  603.     doesn't mean that it comes out in that order. See the "sort"
  604.     entry in the perlfunc manpage for examples of how to arrange for
  605.     an output ordering.
  606.  
  607.   Typeglobs and Filehandles
  608.  
  609.     Perl uses an internal type called a *typeglob* to hold an entire
  610.     symbol table entry. The type prefix of a typeglob is a `*',
  611.     because it represents all types. This used to be the preferred
  612.     way to pass arrays and hashes by reference into a function, but
  613.     now that we have real references, this is seldom needed.
  614.  
  615.     The main use of typeglobs in modern Perl is create symbol table
  616.     aliases. This assignment:
  617.  
  618.         *this = *that;
  619.  
  620.  
  621.     makes $this an alias for $that, @this an alias for @that, %this
  622.     an alias for %that, &this an alias for &that, etc. Much safer is
  623.     to use a reference. This:
  624.  
  625.         local *Here::blue = \$There::green;
  626.  
  627.  
  628.     temporarily makes $Here::blue an alias for $There::green, but
  629.     doesn't make @Here::blue an alias for @There::green, or
  630.     %Here::blue an alias for %There::green, etc. See the section on
  631.     "Symbol Tables" in the perlmod manpage for more examples of
  632.     this. Strange though this may seem, this is the basis for the
  633.     whole module import/export system.
  634.  
  635.     Another use for typeglobs is to to pass filehandles into a
  636.     function or to create new filehandles. If you need to use a
  637.     typeglob to save away a filehandle, do it this way:
  638.  
  639.         $fh = *STDOUT;
  640.  
  641.  
  642.     or perhaps as a real reference, like this:
  643.  
  644.         $fh = \*STDOUT;
  645.  
  646.  
  647.     See the perlsub manpage for examples of using these as indirect
  648.     filehandles in functions.
  649.  
  650.     Typeglobs are also a way to create a local filehandle using the
  651.     local() operator. These last until their block is exited, but
  652.     may be passed back. For example:
  653.  
  654.         sub newopen {
  655.         my $path = shift;
  656.         local *FH;  # not my!
  657.         open   (FH, $path)         or  return undef;
  658.         return *FH;
  659.         }
  660.         $fh = newopen('/etc/passwd');
  661.  
  662.  
  663.     Now that we have the *foo{THING} notation, typeglobs aren't used
  664.     as much for filehandle manipulations, although they're still
  665.     needed to pass brand new file and directory handles into or out
  666.     of functions. That's because *HANDLE{IO} only works if HANDLE
  667.     has already been used as a handle. In other words, *FH can be
  668.     used to create new symbol table entries, but *foo{THING} cannot.
  669.  
  670.     Another way to create anonymous filehandles is with the
  671.     IO::Handle module and its ilk. These modules have the advantage
  672.     of not hiding different types of the same name during the
  673.     local(). See the bottom of the "open()" entry in the perlfunc
  674.     manpage for an example.
  675.  
  676.     See the perlref manpage, the perlsub manpage, and the section on
  677.     "Symbol Tables" in the perlmod manpage for more discussion on
  678.     typeglobs and the *foo{THING} syntax.
  679.  
  680.