Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) SyntaxSubroutine function (Berikutnya)
Language Reference

Perl data types

Daftar Isi

NAME

perldata - Perl data types

DESCRIPTION

Variable names

Perl has three built-in data types: scalars, arrays of scalars, andassociative arrays of scalars, known as "hashes". A scalar is a single string (of any size, limited only by the available memory),number, or a reference to something (which will be discussedin perlref). Normal arrays are ordered lists of scalars indexedby number, starting with 0. Hashes are unordered collections of scalar values indexed by their associated string key.

Values are usually referred to by name, or through a named reference.The first character of the name tells you to what sort of datastructure it refers. The rest of the name tells you the particularvalue to which it refers. Usually this name is a single identifier,that is, a string beginning with a letter or underscore, andcontaining letters, underscores, and digits. In some cases, it maybe a chain of identifiers, separated by :: (or by the slightlyarchaic '); all but the last are interpreted as names of packages,to locate the namespace in which to look up the final identifier(see Packages in perlmod for details). It's possible to substitutefor a simple identifier, an expression that produces a referenceto the value at runtime. This is described in more detail belowand in perlref.

Perl also has its own built-in variables whose names don't followthese rules. They have strange names so they don't accidentallycollide with one of your normal variables. Strings that matchparenthesized parts of a regular expression are saved under namescontaining only digits after the $ (see perlop and perlre).In addition, several special variables that provide windows intothe inner working of Perl have names containing punctuation charactersand control characters. These are documented in perlvar.

Scalar values are always named with '$', even when referring to ascalar that is part of an array or a hash. The '$' symbol workssemantically like the English word "the" in that it indicates asingle value is expected.

  1. $days# the simple scalar value "days"
  2. $days[28]# the 29th element of array @days
  3. $days{'Feb'}# the 'Feb' value from hash %days
  4. $#days# the last index of array @days

Entire arrays (and slices of arrays and hashes) are denoted by '@',which works much as the word "these" or "those" does in English,in that it indicates multiple values are expected.

  1. @days# ($days[0], $days[1],... $days[n])
  2. @days[3,4,5]# same as ($days[3],$days[4],$days[5])
  3. @days{'a','c'}# same as ($days{'a'},$days{'c'})

Entire hashes are denoted by '%':

  1. %days# (key1, val1, key2, val2 ...)

In addition, subroutines are named with an initial '&', though thisis optional when unambiguous, just as the word "do" is often redundantin English. Symbol table entries can be named with an initial '*',but you don't really care about that yet (if ever :-).

Every variable type has its own namespace, as do severalnon-variable identifiers. This means that you can, without fearof conflict, use the same name for a scalar variable, an array, ora hash--or, for that matter, for a filehandle, a directory handle, asubroutine name, a format name, or a label. This means that $fooand @foo are two different variables. It also means that $foo[1]is a part of @foo, not a part of $foo. This may seem a bit weird,but that's okay, because it is weird.

Because variable references always start with '$', '@', or '%', the"reserved" words aren't in fact reserved with respect to variablenames. They are reserved with respect to labels and filehandles,however, which don't have an initial special character. You can'thave a filehandle named "log", for instance. Hint: you could sayopen(LOG,'logfile') rather than open(log,'logfile'). Usinguppercase filehandles also improves readability and protects youfrom conflict with future reserved words. Case is significant--"FOO","Foo", and "foo" are all different names. Names that start with aletter or underscore may also contain digits and underscores.

It is possible to replace such an alphanumeric name with an expressionthat returns a reference to the appropriate type. For a descriptionof this, see perlref.

Names that start with a digit may contain only more digits. Namesthat do not start with a letter, underscore, digit or a caret (i.e.a control character) are limited to one character, e.g., $% or$$. (Most of these one character names have a predefinedsignificance to Perl. For instance, $$ is the current processid.)

Context

The interpretation of operations and values in Perl sometimes dependson the requirements of the context around the operation or value.There are two major contexts: list and scalar. Certain operationsreturn list values in contexts wanting a list, and scalar valuesotherwise. If this is true of an operation it will be mentioned inthe documentation for that operation. In other words, Perl overloadscertain operations based on whether the expected return value issingular or plural. Some words in English work this way, like "fish"and "sheep".

In a reciprocal fashion, an operation provides either a scalar or alist context to each of its arguments. For example, if you say

  1. int( <STDIN> )

the integer operation provides scalar context for the <>operator, which responds by reading one line from STDIN and passing itback to the integer operation, which will then find the integer valueof that line and return that. If, on the other hand, you say

  1. sort( <STDIN> )

then the sort operation provides list context for <>, whichwill proceed to read every line available up to the end of file, andpass that list of lines back to the sort routine, which will thensort those lines and return them as a list to whatever the contextof the sort was.

Assignment is a little bit special in that it uses its left argumentto determine the context for the right argument. Assignment to ascalar evaluates the right-hand side in scalar context, whileassignment to an array or hash evaluates the righthand side in listcontext. Assignment to a list (or slice, which is just a listanyway) also evaluates the right-hand side in list context.

When you use the use warnings pragma or Perl's -w command-line option, you may see warningsabout useless uses of constants or functions in "void context".Void context just means the value has been discarded, such as astatement containing only "fred"; or getpwuid(0);. It stillcounts as scalar context for functions that care whether or notthey're being called in list context.

User-defined subroutines may choose to care whether they are beingcalled in a void, scalar, or list context. Most subroutines do notneed to bother, though. That's because both scalars and lists areautomatically interpolated into lists. See wantarrayfor how you would dynamically discern your function's callingcontext.

Scalar values

All data in Perl is a scalar, an array of scalars, or a hash ofscalars. A scalar may contain one single value in any of threedifferent flavors: a number, a string, or a reference. In general,conversion from one form to another is transparent. Although ascalar may not directly hold multiple values, it may contain areference to an array or hash which in turn contains multiple values.

Scalars aren't necessarily one thing or another. There's no placeto declare a scalar variable to be of type "string", type "number",type "reference", or anything else. Because of the automaticconversion of scalars, operations that return scalars don't needto care (and in fact, cannot care) whether their caller is lookingfor a string, a number, or a reference. Perl is a contextuallypolymorphic language whose scalars can be strings, numbers, orreferences (which includes objects). Although strings and numbersare considered pretty much the same thing for nearly all purposes,references are strongly-typed, uncastable pointers with builtinreference-counting and destructor invocation.

A scalar value is interpreted as FALSE in the Boolean senseif it is undefined, the null string or the number 0 (or itsstring equivalent, "0"), and TRUE if it is anything else. TheBoolean context is just a special kind of scalar context where no conversion to a string or a number is ever performed.

There are actually two varieties of null strings (sometimes referredto as "empty" strings), a defined one and an undefined one. Thedefined version is just a string of length zero, such as "".The undefined version is the value that indicates that there isno real value for something, such as when there was an error, orat end of file, or when you refer to an uninitialized variable orelement of an array or hash. Although in early versions of Perl,an undefined scalar could become defined when first used in aplace expecting a defined value, this no longer happens except forrare cases of autovivification as explained in perlref. You canuse the defined() operator to determine whether a scalar value isdefined (this has no meaning on arrays or hashes), and the undef()operator to produce an undefined value.

To find out whether a given string is a valid non-zero number, it'ssometimes enough to test it against both numeric 0 and also lexical"0" (although this will cause noises if warnings are on). That's because strings that aren't numbers count as 0, just as they do in awk:

  1. if ($str == 0 && $str ne "0") {
  2. warn "That doesn't look like a number";
  3. }

That method may be best because otherwise you won't treat IEEEnotations like NaN or Infinity properly. At other times, youmight prefer to determine whether string data can be used numericallyby calling the POSIX::strtod() function or by inspecting your stringwith a regular expression (as documented in perlre).

  1. warn "has nondigits"if /\D/;
  2. warn "not a natural number" unless /^\d+$/; # rejects -3
  3. warn "not an integer" unless /^-?\d+$/; # rejects +3
  4. warn "not an integer" unless /^[+-]?\d+$/;
  5. warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
  6. warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
  7. warn "not a C float"
  8. unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;

The length of an array is a scalar value. You may find the lengthof array @days by evaluating $#days, as in csh. However, thisisn't the length of the array; it's the subscript of the last element,which is a different value since there is ordinarily a 0th element.Assigning to $#days actually changes the length of the array.Shortening an array this way destroys intervening values. Lengtheningan array that was previously shortened does not recover valuesthat were in those elements. (It used to do so in Perl 4, but wehad to break this to make sure destructors were called when expected.)

You can also gain some minuscule measure of efficiency by pre-extendingan array that is going to get big. You can also extend an arrayby assigning to an element that is off the end of the array. Youcan truncate an array down to nothing by assigning the null list() to it. The following are equivalent:

  1. @whatever = ();
  2. $#whatever = -1;

If you evaluate an array in scalar context, it returns the lengthof the array. (Note that this is not true of lists, which returnthe last value, like the C comma operator, nor of built-in functions,which return whatever they feel like returning.) The following isalways true:

  1. scalar(@whatever) == $#whatever + 1;

Some programmers choose to use an explicit conversion so as to leave nothing to doubt:

  1. $element_count = scalar(@whatever);

If you evaluate a hash in scalar context, it returns false if thehash is empty. If there are any key/value pairs, it returns true;more precisely, the value returned is a string consisting of thenumber of used buckets and the number of allocated buckets, separatedby a slash. This is pretty much useful only to find out whetherPerl's internal hashing algorithm is performing poorly on your dataset. For example, you stick 10,000 things in a hash, but evaluating%HASH in scalar context reveals "1/16", which means only one outof sixteen buckets has been touched, and presumably contains all10,000 of your items. This isn't supposed to happen. If a tied hashis evaluated in scalar context, the SCALAR method is called (with afallback to FIRSTKEY).

You can preallocate space for a hash by assigning to the keys() function.This rounds up the allocated buckets to the next power of two:

  1. keys(%users) = 1000;# allocate 1024 buckets

Scalar value constructors

Numeric literals are specified in any of the following floating point orinteger formats:

  1. 12345
  2. 12345.67
  3. .23E-10 # a very small number
  4. 3.14_15_92 # a very important number
  5. 4_294_967_296 # underscore for legibility
  6. 0xff # hex
  7. 0xdead_beef # more hex
  8. 0377 # octal (only numbers, begins with 0)
  9. 0b011011 # binary

You are allowed to use underscores (underbars) in numeric literalsbetween digits for legibility (but not multiple underscores in a row:23__500 is not legal; 23_500 is).You could, for example, group binarydigits by threes (as for a Unix-style mode argument such as 0b110_100_100)or by fours (to represent nibbles, as in 0b1010_0110) or in other groups.

String literals are usually delimited by either single or doublequotes. They work much like quotes in the standard Unix shells:double-quoted string literals are subject to backslash and variablesubstitution; single-quoted strings are not (except for \' and\). The usual C-style backslash rules apply for makingcharacters such as newline, tab, etc., as well as some more exoticforms. See Quote and Quote-like Operators in perlop for a list.

Hexadecimal, octal, or binary, representations in string literals(e.g. '0xff') are not automatically converted to their integerrepresentation. The hex() and oct() functions make these conversionsfor you. See hex and oct for more details.

You can also embed newlines directly in your strings, i.e., they can endon a different line than they begin. This is nice, but if you forgetyour trailing quote, the error will not be reported until Perl findsanother line containing the quote character, which may be much furtheron in the script. Variable substitution inside strings is limited toscalar variables, arrays, and array or hash slices. (In other words,names beginning with $ or @, followed by an optional bracketedexpression as a subscript.) The following code segment prints out "Theprice is $100."

  1. $Price = '$100';# not interpolated
  2. print "The price is $Price.\n";# interpolated

There is no double interpolation in Perl, so the $100 is left as is.

By default floating point numbers substituted inside strings use thedot (".") as the decimal separator. If use locale is in effect,and POSIX::setlocale() has been called, the character used for thedecimal separator is affected by the LC_NUMERIC locale.See perllocale and POSIX.

As in some shells, you can enclose the variable name in braces todisambiguate it from following alphanumerics (and underscores).You must also dothis when interpolating a variable into a string to separate thevariable name from a following double-colon or an apostrophe, sincethese would be otherwise treated as a package separator:

  1. $who = "Larry";
  2. print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";
  3. print "We use ${who}speak when ${who}'s here.\n";

Without the braces, Perl would have looked for a $whospeak, a$who::0, and a $who's variable. The last two would be the$0 and the $s variables in the (presumably) non-existent packagewho.

In fact, an identifier within such curlies is forced to be a string,as is any simple identifier within a hash subscript. Neither needquoting. Our earlier example, $days{'Feb'} can be written as$days{Feb} and the quotes will be assumed automatically. Butanything more complicated in the subscript will be interpreted as anexpression. This means for example that $version{2.0}++ isequivalent to $version{2}++, not to $version{'2.0'}++.

Version Strings

A literal of the form v1.20.300.4000 is parsed as a string composedof characters with the specified ordinals. This form, known asv-strings, provides an alternative, more readable way to constructstrings, rather than use the somewhat less readable interpolation form"\x{1}\x{14}\x{12c}\x{fa0}". This is useful for representingUnicode strings, and for comparing version "numbers" using the stringcomparison operators, cmp, gt, lt etc. If there are two ormore dots in the literal, the leading v may be omitted.

  1. print v9786; # prints SMILEY, "\x{263a}"
  2. print v102.111.111; # prints "foo"
  3. print 102.111.111; # same

Such literals are accepted by both require and use fordoing a version check. Note that using the v-strings for IPv4addresses is not portable unless you also use theinet_aton()/inet_ntoa() routines of the Socket package.

Note that since Perl 5.8.1 the single-number v-strings (like v65)are not v-strings before the => operator (which is usually usedto separate a hash key from a hash value); instead they are interpretedas literal strings ('v65'). They were v-strings from Perl 5.6.0 toPerl 5.8.0, but that caused more confusion and breakage than good.Multi-number v-strings like v65.66 and 65.66.67 continue tobe v-strings always.

Special Literals

The special literals __FILE__, __LINE__, and __PACKAGE__represent the current filename, line number, and package name at thatpoint in your program. __SUB__ gives a reference to the currentsubroutine. They may be used only as separate tokens; theywill not be interpolated into strings. If there is no current package(due to an empty package; directive), __PACKAGE__ is the undefinedvalue. (But the empty package; is no longer supported, as of version5.10.) Outside of a subroutine, __SUB__ is the undefined value. __SUB__is only available in 5.16 or higher, and only with a use v5.16 oruse feature "current_sub" declaration.

The two control characters ^D and ^Z, and the tokens __END__ and __DATA__may be used to indicate the logical end of the script before the actualend of file. Any following text is ignored.

Text after __DATA__ may be read via the filehandle PACKNAME::DATA,where PACKNAME is the package that was current when the __DATA__token was encountered. The filehandle is left open pointing to theline after __DATA__. The program should close DATA when it is donereading from it. (Leaving it open leaks filehandles if the module isreloaded for any reason, so it's a safer practice to close it.) Forcompatibility with older scripts written before __DATA__ wasintroduced, __END__ behaves like __DATA__ in the top level script (butnot in files loaded with require or do) and leaves the remainingcontents of the file accessible via main::DATA.

See SelfLoader for more description of __DATA__, andan example of its use. Note that you cannot read from the DATAfilehandle in a BEGIN block: the BEGIN block is executed as soonas it is seen (during compilation), at which point the corresponding__DATA__ (or __END__) token has not yet been seen.

Barewords

A word that has no other interpretation in the grammar willbe treated as if it were a quoted string. These are known as"barewords". As with filehandles and labels, a bareword that consistsentirely of lowercase letters risks conflict with future reservedwords, and if you use the use warnings pragma or the -w switch, Perl will warn you about any such words. Perl limits barewords (likeidentifiers) to about 250 characters. Future versions of Perl are likelyto eliminate these arbitrary limitations.

Some people may wish to outlaw barewords entirely. If yousay

  1. use strict 'subs';

then any bareword that would NOT be interpreted as a subroutine callproduces a compile-time error instead. The restriction lasts to theend of the enclosing block. An inner block may countermand thisby saying no strict 'subs'.

Array Interpolation

Arrays and slices are interpolated into double-quoted stringsby joining the elements with the delimiter specified in the $"variable ($LIST_SEPARATOR if "use English;" is specified), space by default. The following are equivalent:

  1. $temp = join($", @ARGV);
  2. system "echo $temp";
  3. system "echo @ARGV";

Within search patterns (which also undergo double-quotish substitution)there is an unfortunate ambiguity: Is /$foo[bar]/ to be interpreted as/${foo}[bar]/ (where [bar] is a character class for the regularexpression) or as /${foo[bar]}/ (where [bar] is the subscript to array@foo)? If @foo doesn't otherwise exist, then it's obviously acharacter class. If @foo exists, Perl takes a good guess about [bar],and is almost always right. If it does guess wrong, or if you're justplain paranoid, you can force the correct interpretation with curlybraces as above.

If you're looking for the information on how to use here-documents,which used to be here, that's been moved toQuote and Quote-like Operators in perlop.

List value constructors

List values are denoted by separating individual values by commas(and enclosing the list in parentheses where precedence requires it):

  1. (LIST)

In a context not requiring a list value, the value of what appearsto be a list literal is simply the value of the final element, aswith the C comma operator. For example,

  1. @foo = ('cc', '-E', $bar);

assigns the entire list value to array @foo, but

  1. $foo = ('cc', '-E', $bar);

assigns the value of variable $bar to the scalar variable $foo.Note that the value of an actual array in scalar context is thelength of the array; the following assigns the value 3 to $foo:

  1. @foo = ('cc', '-E', $bar);
  2. $foo = @foo; # $foo gets 3

You may have an optional comma before the closing parenthesis of alist literal, so that you can say:

  1. @foo = (
  2. 1,
  3. 2,
  4. 3,
  5. );

To use a here-document to assign an array, one line per element,you might use an approach like this:

  1. @sauces = <<End_Lines =~ m/(\S.*\S)/g;
  2. normal tomato
  3. spicy tomato
  4. green chile
  5. pesto
  6. white wine
  7. End_Lines

LISTs do automatic interpolation of sublists. That is, when a LIST isevaluated, each element of the list is evaluated in list context, andthe resulting list value is interpolated into LIST just as if eachindividual element were a member of LIST. Thus arrays and hashes lose theiridentity in a LIST--the list

  1. (@foo,@bar,&SomeSub,%glarch)

contains all the elements of @foo followed by all the elements of @bar,followed by all the elements returned by the subroutine named SomeSub called in list context, followed by the key/value pairs of %glarch.To make a list reference that does NOT interpolate, see perlref.

The null list is represented by (). Interpolating it in a listhas no effect. Thus ((),(),()) is equivalent to (). Similarly,interpolating an array with no elements is the same as if noarray had been interpolated at that point.

This interpolation combines with the facts that the openingand closing parentheses are optional (except when necessary forprecedence) and lists may end with an optional comma to mean thatmultiple commas within lists are legal syntax. The list 1,,3 is aconcatenation of two lists, 1, and 3, the first of which endswith that optional comma. 1,,3 is (1,),(3) is 1,3 (Andsimilarly for 1,,,3 is (1,),(,),3 is 1,3 and so on.) Not thatwe'd advise you to use this obfuscation.

A list value may also be subscripted like a normal array. You mustput the list in parentheses to avoid ambiguity. For example:

  1. # Stat returns list value.
  2. $time = (stat($file))[8];
  3. # SYNTAX ERROR HERE.
  4. $time = stat($file)[8]; # OOPS, FORGOT PARENTHESES
  5. # Find a hex digit.
  6. $hexdigit = ('a','b','c','d','e','f')[$digit-10];
  7. # A "reverse comma operator".
  8. return (pop(@foo),pop(@foo))[0];

Lists may be assigned to only when each element of the listis itself legal to assign to:

  1. ($a, $b, $c) = (1, 2, 3);
  2. ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);

An exception to this is that you may assign to undef in a list.This is useful for throwing away some of the return values of afunction:

  1. ($dev, $ino, undef, undef, $uid, $gid) = stat($file);

List assignment in scalar context returns the number of elementsproduced by the expression on the right side of the assignment:

  1. $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2
  2. $x = (($foo,$bar) = f()); # set $x to f()'s return count

This is handy when you want to do a list assignment in a Booleancontext, because most list functions return a null list when finished,which when assigned produces a 0, which is interpreted as FALSE.

It's also the source of a useful idiom for executing a function orperforming an operation in list context and then counting the number ofreturn values, by assigning to an empty list and then using thatassignment in scalar context. For example, this code:

  1. $count = () = $string =~ /\d+/g;

will place into $count the number of digit groups found in $string.This happens because the pattern match is in list context (since itis being assigned to the empty list), and will therefore return a listof all matching parts of the string. The list assignment in scalarcontext will translate that into the number of elements (here, thenumber of times the pattern matched) and assign that to $count. Notethat simply using

  1. $count = $string =~ /\d+/g;

would not have worked, since a pattern match in scalar context willonly return true or false, rather than a count of matches.

The final element of a list assignment may be an array or a hash:

  1. ($a, $b, @rest) = split;
  2. my($a, $b, %rest) = @_;

You can actually put an array or hash anywhere in the list, but the first onein the list will soak up all the values, and anything after it will becomeundefined. This may be useful in a my() or local().

A hash can be initialized using a literal list holding pairs ofitems to be interpreted as a key and a value:

  1. # same as map assignment above
  2. %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);

While literal lists and named arrays are often interchangeable, that'snot the case for hashes. Just because you can subscript a list value likea normal array does not mean that you can subscript a list value as ahash. Likewise, hashes included as parts of other lists (includingparameters lists and return lists from functions) always flatten out intokey/value pairs. That's why it's good to use references sometimes.

It is often more readable to use the => operator between key/valuepairs. The => operator is mostly just a more visually distinctivesynonym for a comma, but it also arranges for its left-hand operand to beinterpreted as a string if it's a bareword that would be a legal simpleidentifier. => doesn't quote compound identifiers, that containdouble colons. This makes it nice for initializing hashes:

  1. %map = (
  2. red => 0x00f,
  3. blue => 0x0f0,
  4. green => 0xf00,
  5. );

or for initializing hash references to be used as records:

  1. $rec = {
  2. witch => 'Mable the Merciless',
  3. cat => 'Fluffy the Ferocious',
  4. date => '10/31/1776',
  5. };

or for using call-by-named-parameter to complicated functions:

  1. $field = $query->radio_group(
  2. name => 'group_name',
  3. values => ['eenie','meenie','minie'],
  4. default => 'meenie',
  5. linebreak => 'true',
  6. labels => \%labels
  7. );

Note that just because a hash is initialized in that order doesn'tmean that it comes out in that order. See sort for examplesof how to arrange for an output ordering.

Subscripts

An array can be accessed one scalar at atime by specifying a dollar sign ($), then thename of the array (without the leading @), then the subscript insidesquare brackets. For example:

  1. @myarray = (5, 50, 500, 5000);
  2. print "The Third Element is", $myarray[2], "\n";

The array indices start with 0. A negative subscript retrieves its value from the end. In our example, $myarray[-1] would have been 5000, and $myarray[-2] would have been 500.

Hash subscripts are similar, only instead of square brackets curly bracketsare used. For example:

  1. %scientists =
  2. (
  3. "Newton" => "Isaac",
  4. "Einstein" => "Albert",
  5. "Darwin" => "Charles",
  6. "Feynman" => "Richard",
  7. );
  8. print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";

You can also subscript a list to get a single element from it:

  1. $dir = (getpwnam("daemon"))[7];

Multi-dimensional array emulation

Multidimensional arrays may be emulated by subscripting a hash with alist. The elements of the list are joined with the subscript separator(see $; in perlvar).

  1. $foo{$a,$b,$c}

is equivalent to

  1. $foo{join($;, $a, $b, $c)}

The default subscript separator is "\034", the same as SUBSEP in awk.

Slices

A slice accesses several elements of a list, an array, or a hashsimultaneously using a list of subscripts. It's more convenientthan writing out the individual elements as a list of separatescalar values.

  1. ($him, $her) = @folks[0,-1]; # array slice
  2. @them = @folks[0 .. 3]; # array slice
  3. ($who, $home) = @ENV{"USER", "HOME"}; # hash slice
  4. ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice

Since you can assign to a list of variables, you can also assign toan array or hash slice.

  1. @days[3..5] = qw/Wed Thu Fri/;
  2. @colors{'red','blue','green'}
  3. = (0xff0000, 0x0000ff, 0x00ff00);
  4. @folks[0, -1] = @folks[-1, 0];

The previous assignments are exactly equivalent to

  1. ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
  2. ($colors{'red'}, $colors{'blue'}, $colors{'green'})
  3. = (0xff0000, 0x0000ff, 0x00ff00);
  4. ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);

Since changing a slice changes the original array or hash that it'sslicing, a foreach construct will alter some--or even all--of thevalues of the array or hash.

  1. foreach (@array[ 4 .. 10 ]) { s/peter/paul/ }
  2. foreach (@hash{qw[key1 key2]}) {
  3. s/^\s+//; # trim leading whitespace
  4. s/\s+$//; # trim trailing whitespace
  5. s/(\w+)/\u\L$1/g; # "titlecase" words
  6. }

A slice of an empty list is still an empty list. Thus:

  1. @a = ()[1,0]; # @a has no elements
  2. @b = (@a)[0,1]; # @b has no elements
  3. @c = (0,1)[2,3]; # @c has no elements

But:

  1. @a = (1)[1,0]; # @a has two elements
  2. @b = (1,undef)[1,0,2]; # @b has three elements

This makes it easy to write loops that terminate when a null listis returned:

  1. while ( ($home, $user) = (getpwent)[7,0]) {
  2. printf "%-8s %s\n", $user, $home;
  3. }

As noted earlier in this document, the scalar sense of list assignmentis the number of elements on the right-hand side of the assignment.The null list contains no elements, so when the password file isexhausted, the result is 0, not 2.

Slices in scalar context return the last item of the slice.

  1. @a = qw/first second third/;
  2. %h = (first => 'A', second => 'B');
  3. $t = @a[0, 1]; # $t is now 'second'
  4. $u = @h{'first', 'second'}; # $u is now 'B'

If you're confused about why you use an '@' there on a hash sliceinstead of a '%', think of it like this. The type of bracket (squareor curly) governs whether it's an array or a hash being looked at.On the other hand, the leading symbol ('$' or '@') on the array orhash indicates whether you are getting back a singular value (ascalar) or a plural one (a list).

Typeglobs and Filehandles

Perl uses an internal type called a typeglob to hold an entiresymbol table entry. The type prefix of a typeglob is a *, becauseit represents all types. This used to be the preferred way topass arrays and hashes by reference into a function, but now thatwe have real references, this is seldom needed.

The main use of typeglobs in modern Perl is create symbol table aliases.This assignment:

  1. *this = *that;

makes $this an alias for $that, @this an alias for @that, %this an aliasfor %that, &this an alias for &that, etc. Much safer is to use a reference.This:

  1. local *Here::blue = \$There::green;

temporarily makes $Here::blue an alias for $There::green, but doesn'tmake @Here::blue an alias for @There::green, or %Here::blue an alias for%There::green, etc. See Symbol Tables in perlmod for more examplesof this. Strange though this may seem, this is the basis for the wholemodule import/export system.

Another use for typeglobs is to pass filehandles into a function orto create new filehandles. If you need to use a typeglob to save awaya filehandle, do it this way:

  1. $fh = *STDOUT;

or perhaps as a real reference, like this:

  1. $fh = \*STDOUT;

See perlsub for examples of using these as indirect filehandlesin functions.

Typeglobs are also a way to create a local filehandle using the local()operator. These last until their block is exited, but may be passed back.For example:

  1. sub newopen {
  2. my $path = shift;
  3. local *FH; # not my!
  4. open (FH, $path) or return undef;
  5. return *FH;
  6. }
  7. $fh = newopen('/etc/passwd');

Now that we have the *foo{THING} notation, typeglobs aren't used as muchfor filehandle manipulations, although they're still needed to pass brandnew file and directory handles into or out of functions. That's because*HANDLE{IO} only works if HANDLE has already been used as a handle.In other words, *FH must be used to create new symbol table entries;*foo{THING} cannot. When in doubt, use *FH.

All functions that are capable of creating filehandles (open(),opendir(), pipe(), socketpair(), sysopen(), socket(), and accept())automatically create an anonymous filehandle if the handle passed tothem is an uninitialized scalar variable. This allows the constructssuch as open(my $fh, ...) and open(local $fh,...) to be used tocreate filehandles that will conveniently be closed automatically whenthe scope ends, provided there are no other references to them. Thislargely eliminates the need for typeglobs when opening filehandlesthat must be passed around, as in the following example:

  1. sub myopen {
  2. open my $fh, "@_"
  3. or die "Can't open '@_': $!";
  4. return $fh;
  5. }
  6. {
  7. my $f = myopen("</etc/motd");
  8. print <$f>;
  9. # $f implicitly closed here
  10. }

Note that if an initialized scalar variable is used instead theresult is different: my $fh='zzz'; open($fh, ...) is equivalentto open( *{'zzz'}, ...).use strict 'refs' forbids such practice.

Another way to create anonymous filehandles is with the Symbolmodule or with the IO::Handle module and its ilk. These moduleshave the advantage of not hiding different types of the same nameduring the local(). See the bottom of open for anexample.

SEE ALSO

See perlvar for a description of Perl's built-in variables anda discussion of legal variable names. See perlref, perlsub,and Symbol Tables in perlmod for more discussion on typeglobs andthe *foo{THING} syntax.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) SyntaxSubroutine function (Berikutnya)