X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=pod%2Fperldata.pod;h=d828d4aca761a0148d1dc361a82dcb51a583b8a5;hb=cf2649810f00335bd657355d81bcc9384a620135;hp=b7c3b1cecd342daa728d2326164e8122df33e409;hpb=d4ced10d0773d7b2aaa8e52df351060660783e30;p=p5sagit%2Fp5-mst-13.2.git diff --git a/pod/perldata.pod b/pod/perldata.pod index b7c3b1c..d828d4a 100644 --- a/pod/perldata.pod +++ b/pod/perldata.pod @@ -7,10 +7,12 @@ perldata - Perl data types =head2 Variable names Perl has three built-in data types: scalars, arrays of scalars, and -associative arrays of scalars, known as "hashes". Normal arrays -are ordered lists of scalars indexed by number, starting with 0 and with -negative subscripts counting from the end. Hashes are unordered -collections of scalar values indexed by their associated string key. +associative 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 discussed +in L). Normal arrays are ordered lists of scalars indexed +by 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 data @@ -87,10 +89,11 @@ that returns a reference to the appropriate type. For a description of this, see L. Names that start with a digit may contain only more digits. Names -that do not start with a letter, underscore, or digit are limited to -one character, e.g., C<$%> or C<$$>. (Most of these one character names -have a predefined significance to Perl. For instance, C<$$> is the -current process id.) +that do not start with a letter, underscore, digit or a caret (i.e. +a control character) are limited to one character, e.g., C<$%> or +C<$$>. (Most of these one character names have a predefined +significance to Perl. For instance, C<$$> is the current process +id.) =head2 Context @@ -186,8 +189,8 @@ operator to produce an undefined value. To find out whether a given string is a valid non-zero number, it's sometimes enough to test it against both numeric 0 and also lexical -"0" (although this will cause B<-w> noises). That's because strings -that aren't numbers count as 0, just as they do in B: +"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 B: if ($str == 0 && $str ne "0") { warn "That doesn't look like a number"; @@ -218,7 +221,7 @@ an array that was previously shortened does not recover values that were in those elements. (It used to do so in Perl 4, but we had to break this to make sure destructors were called when expected.) -You can also gain some miniscule measure of efficiency by pre-extending +You can also gain some minuscule measure of efficiency by pre-extending an array that is going to get big. You can also extend an array by assigning to an element that is off the end of the array. You can truncate an array down to nothing by assigning the null list @@ -256,7 +259,9 @@ Perl's internal hashing algorithm is performing poorly on your data set. For example, you stick 10,000 things in a hash, but evaluating %HASH in scalar context reveals C<"1/16">, which means only one out of sixteen buckets has been touched, and presumably contains all -10,000 of your items. This isn't supposed to happen. +10,000 of your items. This isn't supposed to happen. If a tied hash +is evaluated in scalar context, a fatal error will result, since this +bucket usage information is currently not available for tied hashes. 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: @@ -275,7 +280,7 @@ integer formats: 4_294_967_296 # underscore for legibility 0xff # hex 0xdead_beef # more hex - 0377 # octal + 0377 # octal (only numbers, begins with 0) 0b011011 # binary You are allowed to use underscores (underbars) in numeric literals @@ -306,8 +311,10 @@ names beginning with $ or @, followed by an optional bracketed expression as a subscript.) The following code segment prints out "The price is $Z<>100." - $Price = '$100'; # not interpreted - print "The price is $Price.\n"; # interpreted + $Price = '$100'; # not interpolated + print "The price is $Price.\n"; # interpolated + +There is no double interpolation in Perl, so the C<$100> is left as is. As in some shells, you can enclose the variable name in braces to disambiguate it from following alphanumerics (and underscores). @@ -329,17 +336,25 @@ In fact, an identifier within such curlies is forced to be a string, as is any simple identifier within a hash subscript. Neither need quoting. Our earlier example, C<$days{'Feb'}> can be written as C<$days{Feb}> and the quotes will be assumed automatically. But -anything more complicated in the subscript will be interpreted as -an expression. +anything more complicated in the subscript will be interpreted as an +expression. This means for example that C<$version{2.0}++> is +equivalent to C<$version{2}++>, not to C<$version{'2.0'}++>. + +=head3 Version Strings + +B Version Strings (v-strings) have been deprecated. They will +be removed in some future release after Perl 5.8.1. The marginal +benefits of v-strings were greatly outweighed by the potential for +Surprise and Confusion. A literal of the form C is parsed as a string composed -of characters with the specified ordinals. This provides an alternative, -more readable way to construct strings, rather than use the somewhat less -readable interpolation form C<"\x{1}\x{14}\x{12c}\x{fa0}">. This is useful -for representing Unicode strings, and for comparing version "numbers" -using the string comparison operators, C, C, C etc. -If there are two or more dots in the literal, the leading C may be -omitted. +of characters with the specified ordinals. This form, known as +v-strings, provides an alternative, more readable way to construct +strings, rather than use the somewhat less readable interpolation form +C<"\x{1}\x{14}\x{12c}\x{fa0}">. This is useful for representing +Unicode strings, and for comparing version "numbers" using the string +comparison operators, C, C, C etc. If there are two or +more dots in the literal, the leading C may be omitted. print v9786; # prints UTF-8 encoded SMILEY, "\x{263a}" print v102.111.111; # prints "foo" @@ -348,6 +363,18 @@ omitted. Such literals are accepted by both C and C for doing a version check. The C<$^V> special variable also contains the running Perl interpreter's version in this form. See L. +Note that using the v-strings for IPv4 addresses is not portable unless +you also use the inet_aton()/inet_ntoa() routines of the Socket package. + +Note that since Perl 5.8.1 the single-number v-strings (like C) +are not v-strings before the C<< => >> operator (which is usually used +to separate a hash key from a hash value), instead they are interpreted +as literal strings ('v65'). They were v-strings from Perl 5.6.0 to +Perl 5.8.0, but that caused more confusion and breakage than good. +Multi-number v-strings like C and C<65.66.67> continue to +be v-strings always. + +=head3 Special Literals The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that @@ -376,6 +403,8 @@ filehandle in a BEGIN block: the BEGIN block is executed as soon as it is seen (during compilation), at which point the corresponding __DATA__ (or __END__) token has not yet been seen. +=head3 Barewords + A word that has no other interpretation in the grammar will be treated as if it were a quoted string. These are known as "barewords". As with filehandles and labels, a bareword that consists @@ -392,10 +421,12 @@ produces a compile-time error instead. The restriction lasts to the end of the enclosing block. An inner block may countermand this by saying C. +=head3 Array Joining Delimiter + Arrays and slices are interpolated into double-quoted strings by joining the elements with the delimiter specified in the C<$"> -variable (C<$LIST_SEPARATOR> in English), space by default. The -following are equivalent: +variable (C<$LIST_SEPARATOR> if "use English;" is specified), +space by default. The following are equivalent: $temp = join($", @ARGV); system "echo $temp"; @@ -412,95 +443,9 @@ and is almost always right. If it does guess wrong, or if you're just plain paranoid, you can force the correct interpretation with curly braces as above. -A line-oriented form of quoting is based on the shell "here-document" -syntax. Following a C<< << >> you specify a string to terminate -the quoted material, and all lines following the current line down to -the terminating string are the value of the item. The terminating -string may be either an identifier (a word), or some quoted text. If -quoted, the type of quotes you use determines the treatment of the -text, just as in regular quoting. An unquoted identifier works like -double quotes. There must be no space between the C<< << >> and -the identifier, unless the identifier is quoted. (If you put a space it -will be treated as a null identifier, which is valid, and matches the first -empty line.) The terminating string must appear by itself (unquoted and -with no surrounding whitespace) on the terminating line. - - print <, -the quoted material must come on the lines following the final delimiter. -So instead of - - s/this/<. - -Additionally, the quoting rules for the identifier are not related to -Perl's quoting rules -- C, C, and the like are not supported -in place of C<''> and C<"">, and the only interpolation is for backslashing -the quoting character: - - print << "abc\"def"; - testing... - abc"def - -Finally, quoted strings cannot span multiple lines. The general rule is -that the identifier must be a string literal. Stick with that, and you -should be safe. +If you're looking for the information on how to use here-documents, +which used to be here, that's been moved to +L. =head2 List value constructors @@ -524,26 +469,26 @@ Note that the value of an actual array in scalar context is the length of the array; the following assigns the value 3 to $foo: @foo = ('cc', '-E', $bar); - $foo = @foo; # $foo gets 3 + $foo = @foo; # $foo gets 3 You may have an optional comma before the closing parenthesis of a list literal, so that you can say: @foo = ( - 1, - 2, - 3, + 1, + 2, + 3, ); To use a here-document to assign an array, one line per element, you might use an approach like this: @sauces = < is a concatenation of two lists, C<1,> and C<3>, the first of which ends @@ -604,14 +549,34 @@ function: List assignment in scalar context returns the number of elements produced by the expression on the right side of the assignment: - $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 2 - $x = (($foo,$bar) = f()); # set $x to f()'s return count + $x = (($foo,$bar) = (3,2,1)); # set $x to 3, not 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 Boolean context, because most list functions return a null list when finished, which when assigned produces a 0, which is interpreted as FALSE. -The final element may be an array or a hash: +It's also the source of a useful idiom for executing a function or +performing an operation in list context and then counting the number of +return values, by assigning to an empty list and then using that +assignment in scalar context. For example, this code: + + $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 it +is being assigned to the empty list), and will therefore return a list +of all matching parts of the string. The list assignment in scalar +context will translate that into the number of elements (here, the +number of times the pattern matched) and assign that to $count. Note +that simply using + + $count = $string =~ /\d+/g; + +would not have worked, since a pattern match in scalar context will +only return true or false, rather than a count of matches. + +The final element of a list assignment may be an array or a hash: ($a, $b, @rest) = split; my($a, $b, %rest) = @_; @@ -636,27 +601,28 @@ key/value pairs. That's why it's good to use references sometimes. It is often more readable to use the C<< => >> operator between key/value pairs. The C<< => >> operator is mostly just a more visually distinctive synonym for a comma, but it also arranges for its left-hand operand to be -interpreted as a string--if it's a bareword that would be a legal identifier. -This makes it nice for initializing hashes: +interpreted as a string -- if it's a bareword that would be a legal simple +identifier (C<< => >> doesn't quote compound identifiers, that contain +double colons). This makes it nice for initializing hashes: %map = ( - red => 0x00f, - blue => 0x0f0, - green => 0xf00, + red => 0x00f, + blue => 0x0f0, + green => 0xf00, ); or for initializing hash references to be used as records: $rec = { - witch => 'Mable the Merciless', - cat => 'Fluffy the Ferocious', - date => '10/31/1776', + witch => 'Mable the Merciless', + cat => 'Fluffy the Ferocious', + date => '10/31/1776', }; or for using call-by-named-parameter to complicated functions: $field = $query->radio_group( - name => 'group_name', + name => 'group_name', values => ['eenie','meenie','minie'], default => 'meenie', linebreak => 'true', @@ -667,39 +633,65 @@ Note that just because a hash is initialized in that order doesn't mean that it comes out in that order. See L for examples of how to arrange for an output ordering. +=head2 Subscripts + +An array is subscripted by specifying a dollar sign (C<$>), then the +name of the array (without the leading C<@>), then the subscript inside +square brackets. For example: + + @myarray = (5, 50, 500, 5000); + print "Element Number 2 is", $myarray[2], "\n"; + +The array indices start with 0. A negative subscript retrieves its +value from the end. In our example, C<$myarray[-1]> would have been +5000, and C<$myarray[-2]> would have been 500. + +Hash subscripts are similar, only instead of square brackets curly brackets +are used. For example: + + %scientists = + ( + "Newton" => "Isaac", + "Einstein" => "Albert", + "Darwin" => "Charles", + "Feynman" => "Richard", + ); + + print "Darwin's First Name is ", $scientists{"Darwin"}, "\n"; + =head2 Slices A common way to access an array or a hash is one scalar element at a time. You can also subscript a list to get a single element from it. - $whoami = $ENV{"USER"}; # one element from the hash - $parent = $ISA[0]; # one element from the array - $dir = (getpwnam("daemon"))[7]; # likewise, but with list + $whoami = $ENV{"USER"}; # one element from the hash + $parent = $ISA[0]; # one element from the array + $dir = (getpwnam("daemon"))[7]; # likewise, but with list A slice accesses several elements of a list, an array, or a hash simultaneously using a list of subscripts. It's more convenient than writing out the individual elements as a list of separate scalar values. - ($him, $her) = @folks[0,-1]; # array slice - @them = @folks[0 .. 3]; # array slice - ($who, $home) = @ENV{"USER", "HOME"}; # hash slice - ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice + ($him, $her) = @folks[0,-1]; # array slice + @them = @folks[0 .. 3]; # array slice + ($who, $home) = @ENV{"USER", "HOME"}; # hash slice + ($uid, $dir) = (getpwnam("daemon"))[2,7]; # list slice Since you can assign to a list of variables, you can also assign to an array or hash slice. @days[3..5] = qw/Wed Thu Fri/; @colors{'red','blue','green'} - = (0xff0000, 0x0000ff, 0x00ff00); + = (0xff0000, 0x0000ff, 0x00ff00); @folks[0, -1] = @folks[-1, 0]; The previous assignments are exactly equivalent to ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/; ($colors{'red'}, $colors{'blue'}, $colors{'green'}) - = (0xff0000, 0x0000ff, 0x00ff00); - ($folks[0], $folks[-1]) = ($folks[0], $folks[-1]); + = (0xff0000, 0x0000ff, 0x00ff00); + ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]); Since changing a slice changes the original array or hash that it's slicing, a C construct will alter some--or even all--of the @@ -707,10 +699,10 @@ values of the array or hash. foreach (@array[ 4 .. 10 ]) { s/peter/paul/ } - foreach (@hash{keys %hash}) { - s/^\s+//; # trim leading whitespace - s/\s+$//; # trim trailing whitespace - s/(\w+)/\u\L$1/g; # "titlecase" words + foreach (@hash{qw[key1 key2]}) { + s/^\s+//; # trim leading whitespace + s/\s+$//; # trim trailing whitespace + s/(\w+)/\u\L$1/g; # "titlecase" words } A slice of an empty list is still an empty list. Thus: @@ -728,7 +720,7 @@ This makes it easy to write loops that terminate when a null list is returned: while ( ($home, $user) = (getpwent)[7,0]) { - printf "%-8s %s\n", $user, $home; + printf "%-8s %s\n", $user, $home; } As noted earlier in this document, the scalar sense of list assignment @@ -786,10 +778,10 @@ operator. These last until their block is exited, but may be passed back. For example: sub newopen { - my $path = shift; - local *FH; # not my! - open (FH, $path) or return undef; - return *FH; + my $path = shift; + local *FH; # not my! + open (FH, $path) or return undef; + return *FH; } $fh = newopen('/etc/passwd'); @@ -812,16 +804,21 @@ that must be passed around, as in the following example: sub myopen { open my $fh, "@_" - or die "Can't open '@_': $!"; - return $fh; + or die "Can't open '@_': $!"; + return $fh; } { my $f = myopen("; - # $f implicitly closed here + print <$f>; + # $f implicitly closed here } +Note that if an initialized scalar variable is used instead the +result is different: C is equivalent +to C. +C forbids such practice. + Another way to create anonymous filehandles is with the Symbol module or with the IO::Handle module and its ilk. These modules have the advantage of not hiding different types of the same name