This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fix line containing only whitespace.
[perl5.git] / pod / perlfaq4.pod
index b4945d3..c870918 100644 (file)
@@ -1,6 +1,6 @@
 =head1 NAME
 
-perlfaq4 - Data Manipulation ($Revision: 7996 $)
+perlfaq4 - Data Manipulation
 
 =head1 DESCRIPTION
 
@@ -11,17 +11,21 @@ numbers, dates, strings, arrays, hashes, and miscellaneous data issues.
 
 =head2 Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?
 
+For the long explanation, see David Goldberg's "What Every Computer
+Scientist Should Know About Floating-Point Arithmetic"
+(http://docs.sun.com/source/806-3568/ncg_goldberg.html).
+
 Internally, your computer represents floating-point numbers in binary.
 Digital (as in powers of two) computers cannot store all numbers
 exactly.  Some real numbers lose precision in the process.  This is a
 problem with how computers store numbers and affects all computer
 languages, not just Perl.
 
-L<perlnumber> show the gory details of number representations and
+L<perlnumber> shows the gory details of number representations and
 conversions.
 
 To limit the number of decimal places in your numbers, you can use the
-printf or sprintf function.  See the L<"Floating Point
+C<printf> or C<sprintf> function.  See the L<"Floating Point
 Arithmetic"|perlop> for more details.
 
        printf "%.2f", 10/3;
@@ -48,35 +52,45 @@ numbers.  What you think in the above as 'three' is really more like
 
 =head2 Why isn't my octal data interpreted correctly?
 
-Perl only understands octal and hex numbers as such when they occur as
-literals in your program.  Octal literals in perl must start with a
-leading C<0> and hexadecimal literals must start with a leading C<0x>.
-If they are read in from somewhere and assigned, no automatic
-conversion takes place.  You must explicitly use C<oct()> or C<hex()> if you
-want the values converted to decimal.  C<oct()> interprets hexadecimal (C<0x350>),
-octal (C<0350> or even without the leading C<0>, like C<377>) and binary
-(C<0b1010>) numbers, while C<hex()> only converts hexadecimal ones, with
-or without a leading C<0x>, such as C<0x255>, C<3A>, C<ff>, or C<deadbeef>.
-The inverse mapping from decimal to octal can be done with either the
-<%o> or C<%O> C<sprintf()> formats.
+(contributed by brian d foy)
+
+You're probably trying to convert a string to a number, which Perl only
+converts as a decimal number. When Perl converts a string to a number, it
+ignores leading spaces and zeroes, then assumes the rest of the digits
+are in base 10:
+
+       my $string = '0644';
+
+       print $string + 0;  # prints 644
+
+       print $string + 44; # prints 688, certainly not octal!
+
+This problem usually involves one of the Perl built-ins that has the
+same name a Unix command that uses octal numbers as arguments on the
+command line. In this example, C<chmod> on the command line knows that
+its first argument is octal because that's what it does:
 
-This problem shows up most often when people try using C<chmod()>,
-C<mkdir()>, C<umask()>, or C<sysopen()>, which by widespread tradition
-typically take permissions in octal.
+       %prompt> chmod 644 file
 
-       chmod(644,  $file);   # WRONG
-       chmod(0644, $file);   # right
+If you want to use the same literal digits (644) in Perl, you have to tell
+Perl to treat them as octal numbers either by prefixing the digits with
+a C<0> or using C<oct>:
 
-Note the mistake in the first line was specifying the decimal literal
-C<644>, rather than the intended octal literal C<0644>.  The problem can
-be seen with:
+       chmod(     0644, $file);   # right, has leading zero
+       chmod( oct(644), $file );  # also correct
 
-       printf("%#o",644);   # prints 01204
+The problem comes in when you take your numbers from something that Perl
+thinks is a string, such as a command line argument in C<@ARGV>:
 
-Surely you had not intended C<chmod(01204, $file);> - did you?  If you
-want to use numeric literals as arguments to chmod() et al. then please
-try to express them as octal constants, that is with a leading zero and
-with the following digits restricted to the set C<0..7>.
+       chmod( $ARGV[0],      $file);   # wrong, even if "0644"
+
+       chmod( oct($ARGV[0]), $file );  # correct, treat string as octal
+
+You can always check the value you're using by printing it in octal
+notation to ensure it matches what you think it should be. Print it
+in octal  and decimal format:
+
+       printf "0%o %d", $number, $number;
 
 =head2 Does Perl have a round() function?  What about ceil() and floor()?  Trig functions?
 
@@ -287,8 +301,8 @@ but a string consisting of two null bytes (the result of C<"\020\020"
 
 =head2 How do I multiply matrices?
 
-Use the Math::Matrix or Math::MatrixReal modules (available from CPAN)
-or the PDL extension (also available from CPAN).
+Use the C<Math::Matrix> or C<Math::MatrixReal> modules (available from CPAN)
+or the C<PDL> extension (also available from CPAN).
 
 =head2 How do I perform an operation on a series of integers?
 
@@ -317,7 +331,7 @@ all integers in the range.  This can take a lot of memory for large
 ranges.  Instead use:
 
        @results = ();
-       for ($i=5; $i < 500_005; $i++) {
+       for ($i=5; $i <= 500_005; $i++) {
                push(@results, some_func($i));
                }
 
@@ -332,7 +346,7 @@ will not create a list of 500,000 integers.
 
 =head2 How can I output Roman numerals?
 
-Get the http://www.cpan.org/modules/by-module/Roman module.
+Get the L<http://www.cpan.org/modules/by-module/Roman> module.
 
 =head2 Why aren't my random numbers random?
 
@@ -348,7 +362,7 @@ rather than more.
 Computers are good at being predictable and bad at being random
 (despite appearances caused by bugs in your programs :-).  see the
 F<random> article in the "Far More Than You Ever Wanted To Know"
-collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz , courtesy
+collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz>, courtesy
 of Tom Phoenix, talks more about this.  John von Neumann said, "Anyone
 who attempts to generate random numbers by deterministic means is, of
 course, living in a state of sin."
@@ -358,23 +372,22 @@ provides, you should also check out the C<Math::TrulyRandom> module from
 CPAN.  It uses the imperfections in your system's timer to generate
 random numbers, but this takes quite a while.  If you want a better
 pseudorandom generator than comes with your operating system, look at
-"Numerical Recipes in C" at http://www.nr.com/ .
+"Numerical Recipes in C" at L<http://www.nr.com/>.
 
 =head2 How do I get a random number between X and Y?
 
-To get a random number between two values, you can use the
-C<rand()> builtin to get a random number between 0 and
+To get a random number between two values, you can use the C<rand()>
+built-in to get a random number between 0 and 1. From there, you shift
+that into the range that you want.
 
-C<rand($x)> returns a number such that
-C<< 0 <= rand($x) < $x >>. Thus what you want to have perl
-figure out is a random number in the range from 0 to the
-difference between your I<X> and I<Y>.
+C<rand($x)> returns a number such that C<< 0 <= rand($x) < $x >>. Thus
+what you want to have perl figure out is a random number in the range
+from 0 to the difference between your I<X> and I<Y>.
 
-That is, to get a number between 10 and 15, inclusive, you
-want a random number between 0 and 5 that you can then add
-to 10.
+That is, to get a number between 10 and 15, inclusive, you want a
+random number between 0 and 5 that you can then add to 10.
 
-       my $number = 10 + int rand( 15-10+1 );
+       my $number = 10 + int rand( 15-10+1 ); # ( 10,11,12,13,14, or 15 )
 
 Hence you derive the following simple function to abstract
 that. It selects a random integer between the two given
@@ -392,8 +405,8 @@ integers (inclusive), For example: C<random_int_between(50,120)>.
 
 =head2 How do I find the day or week of the year?
 
-The localtime function returns the day of the year.  Without an
-argument localtime uses the current time.
+The C<localtime> function returns the day of the year.  Without an
+argument C<localtime> uses the current time.
 
        $day_of_year = (localtime)[7];
 
@@ -405,7 +418,7 @@ week of the year.
        my $week_of_year = strftime "%W", localtime;
 
 To get the day of year for any date, use C<POSIX>'s C<mktime> to get
-a time in epoch seconds for the argument to localtime.
+a time in epoch seconds for the argument to C<localtime>.
 
        use POSIX qw/mktime strftime/;
        my $week_of_year = strftime "%W",
@@ -479,6 +492,9 @@ Julian day)
        31
 
 =head2 How do I find yesterday's date?
+X<date> X<yesterday> X<DateTime> X<Date::Calc> X<Time::Local>
+X<daylight saving time> X<day> X<Today_and_Now> X<localtime>
+X<timelocal>
 
 (contributed by brian d foy)
 
@@ -491,49 +507,60 @@ give you the same time of day, only the day before.
 
        print "Yesterday was $yesterday\n";
 
-You can also use the C<Date::Calc> module using its Today_and_Now
+You can also use the C<Date::Calc> module using its C<Today_and_Now>
 function.
 
        use Date::Calc qw( Today_and_Now Add_Delta_DHMS );
 
        my @date_time = Add_Delta_DHMS( Today_and_Now(), -1, 0, 0, 0 );
 
-       print "@date\n";
+       print "@date_time\n";
 
 Most people try to use the time rather than the calendar to figure out
 dates, but that assumes that days are twenty-four hours each.  For
 most people, there are two days a year when they aren't: the switch to
 and from summer time throws this off. Let the modules do the work.
 
-=head2 Does Perl have a Year 2000 problem? Is Perl Y2K compliant?
+If you absolutely must do it yourself (or can't use one of the
+modules), here's a solution using C<Time::Local>, which comes with
+Perl:
+
+       # contributed by Gunnar Hjalmarsson
+        use Time::Local;
+        my $today = timelocal 0, 0, 12, ( localtime )[3..5];
+        my ($d, $m, $y) = ( localtime $today-86400 )[3..5];
+        printf "Yesterday: %d-%02d-%02d\n", $y+1900, $m+1, $d;
+
+In this case, you measure the day starting at noon, and subtract 24
+hours. Even if the length of the calendar day is 23 or 25 hours,
+you'll still end up on the previous calendar day, although not at
+noon. Since you don't care about the time, the one hour difference
+doesn't matter and you end up with the previous date.
+
+=head2 Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?
 
-Short answer: No, Perl does not have a Year 2000 problem.  Yes, Perl is
-Y2K compliant (whatever that means). The programmers you've hired to
-use it, however, probably are not.
+(contributed by brian d foy)
+
+Perl itself never had a Y2K problem, although that never stopped people
+from creating Y2K problems on their own. See the documentation for
+C<localtime> for its proper use.
 
-Long answer: The question belies a true understanding of the issue.
-Perl is just as Y2K compliant as your pencil--no more, and no less.
-Can you use your pencil to write a non-Y2K-compliant memo?  Of course
-you can.  Is that the pencil's fault?  Of course it isn't.
+Starting with Perl 5.11, C<localtime> and C<gmtime> can handle dates past
+03:14:08 January 19, 2038, when a 32-bit based time would overflow. You
+still might get a warning on a 32-bit C<perl>:
 
-The date and time functions supplied with Perl (gmtime and localtime)
-supply adequate information to determine the year well beyond 2000
-(2038 is when trouble strikes for 32-bit machines).  The year returned
-by these functions when used in a list context is the year minus 1900.
-For years between 1910 and 1999 this I<happens> to be a 2-digit decimal
-number. To avoid the year 2000 problem simply do not treat the year as
-a 2-digit number.  It isn't.
+       % perl5.11.2 -E 'say scalar localtime( 0x9FFF_FFFFFFFF )'
+       Integer overflow in hexadecimal number at -e line 1.
+       Wed Nov  1 19:42:39 5576711
 
-When gmtime() and localtime() are used in scalar context they return
-a timestamp string that contains a fully-expanded year.  For example,
-C<$timestamp = gmtime(1005613200)> sets $timestamp to "Tue Nov 13 01:00:00
-2001".  There's no year 2000 problem here.
+On a 64-bit C<perl>, you can get even larger dates for those really long
+running projects:
 
-That doesn't mean that Perl can't be used to create non-Y2K compliant
-programs.  It can.  But so can your pencil.  It's the fault of the user,
-not the language.  At the risk of inflaming the NRA: "Perl doesn't
-break Y2K, people do."  See http://www.perl.org/about/y2k.html for
-a longer exposition.
+       % perl5.11.2 -E 'say scalar gmtime( 0x9FFF_FFFFFFFF )'
+       Thu Nov  2 00:42:39 5576711
+
+You're still out of luck if you need to keep track of decaying protons
+though.
 
 =head1 Data: Strings
 
@@ -567,11 +594,11 @@ This won't expand C<"\n"> or C<"\t"> or any other special escapes.
 You can use the substitution operator to find pairs of characters (or
 runs of characters) and replace them with a single instance. In this
 substitution, we find a character in C<(.)>. The memory parentheses
-store the matched character in the back-reference C<\1> and we use
+store the matched character in the back-reference C<\g1> and we use
 that to require that the same thing immediately follow it. We replace
 that part of the string with the character in C<$1>.
 
-       s/(.)\1/$1/g;
+       s/(.)\g1/$1/g;
 
 We can also use the transliteration operator, C<tr///>. In this
 example, the search list side of our C<tr///> contains nothing, but
@@ -782,14 +809,33 @@ result to a scalar, producing a count of the number of matches.
        $count = () = $string =~ /-\d+/g;
 
 =head2 How do I capitalize all the words on one line?
+X<Text::Autoformat> X<capitalize> X<case, title> X<case, sentence>
 
-To make the first letter of each word upper case:
+(contributed by brian d foy)
 
-       $line =~ s/\b(\w)/\U$1/g;
+Damian Conway's L<Text::Autoformat> handles all of the thinking
+for you.
+
+       use Text::Autoformat;
+       my $x = "Dr. Strangelove or: How I Learned to Stop ".
+         "Worrying and Love the Bomb";
+
+       print $x, "\n";
+       for my $style (qw( sentence title highlight )) {
+               print autoformat($x, { case => $style }), "\n";
+               }
 
-This has the strange effect of turning "C<don't do it>" into "C<Don'T
-Do It>".  Sometimes you might want this.  Other times you might need a
-more thorough solution (Suggested by brian d foy):
+How do you want to capitalize those words?
+
+       FRED AND BARNEY'S LODGE        # all uppercase
+       Fred And Barney's Lodge        # title case
+       Fred and Barney's Lodge        # highlight case
+
+It's not as easy a problem as it looks. How many words do you think
+are in there? Wait for it... wait for it.... If you answered 5
+you're right. Perl words are groups of C<\w+>, but that's not what
+you want to capitalize. How is Perl supposed to know not to capitalize
+that C<s> after the apostrophe? You could try a regular expression:
 
        $string =~ s/ (
                                 (^\w)    #at the beginning of the line
@@ -800,34 +846,8 @@ more thorough solution (Suggested by brian d foy):
 
        $string =~ s/([\w']+)/\u\L$1/g;
 
-To make the whole line upper case:
-
-       $line = uc($line);
-
-To force each word to be lower case, with the first letter upper case:
-
-       $line =~ s/(\w+)/\u\L$1/g;
-
-You can (and probably should) enable locale awareness of those
-characters by placing a C<use locale> pragma in your program.
-See L<perllocale> for endless details on locales.
-
-This is sometimes referred to as putting something into "title
-case", but that's not quite accurate.  Consider the proper
-capitalization of the movie I<Dr. Strangelove or: How I Learned to
-Stop Worrying and Love the Bomb>, for example.
-
-Damian Conway's L<Text::Autoformat> module provides some smart
-case transformations:
-
-       use Text::Autoformat;
-       my $x = "Dr. Strangelove or: How I Learned to Stop ".
-         "Worrying and Love the Bomb";
-
-       print $x, "\n";
-       for my $style (qw( sentence title highlight )) {
-               print autoformat($x, { case => $style }), "\n";
-               }
+Now, what if you don't want to capitalize that "and"? Just use
+L<Text::Autoformat> and get on with the next problem. :)
 
 =head2 How can I split a [character] delimited string except when inside [character]?
 
@@ -870,14 +890,14 @@ Perl distribution) lets you say:
 
 A substitution can do this for you. For a single line, you want to
 replace all the leading or trailing whitespace with nothing. You
-can do that with a pair of substitutions.
+can do that with a pair of substitutions:
 
        s/^\s+//;
        s/\s+$//;
 
 You can also write that as a single substitution, although it turns
 out the combined statement is slower than the separate ones. That
-might not matter to you, though.
+might not matter to you, though:
 
        s/^\s+|\s+$//g;
 
@@ -886,30 +906,29 @@ beginning or the end of the string since the anchors have a lower
 precedence than the alternation. With the C</g> flag, the substitution
 makes all possible matches, so it gets both. Remember, the trailing
 newline matches the C<\s+>, and  the C<$> anchor can match to the
-physical end of the string, so the newline disappears too. Just add
+absolute end of the string, so the newline disappears too. Just add
 the newline to the output, which has the added benefit of preserving
 "blank" (consisting entirely of whitespace) lines which the C<^\s+>
-would remove all by itself.
+would remove all by itself:
 
-       while( <> )
-               {
+       while( <> ) {
                s/^\s+|\s+$//g;
                print "$_\n";
                }
 
-For a multi-line string, you can apply the regular expression
-to each logical line in the string by adding the C</m> flag (for
+For a multi-line string, you can apply the regular expression to each
+logical line in the string by adding the C</m> flag (for
 "multi-line"). With the C</m> flag, the C<$> matches I<before> an
-embedded newline, so it doesn't remove it. It still removes the
-newline at the end of the string.
+embedded newline, so it doesn't remove it. This pattern still removes
+the newline at the end of the string:
 
        $string =~ s/^\s+|\s+$//gm;
 
 Remember that lines consisting entirely of whitespace will disappear,
 since the first part of the alternation can match the entire string
-and replace it with nothing. If need to keep embedded blank lines,
+and replace it with nothing. If you need to keep embedded blank lines,
 you have to do a little more work. Instead of matching any whitespace
-(since that includes a newline), just match the other whitespace.
+(since that includes a newline), just match the other whitespace:
 
        $string =~ s/^[\t\f ]+|[\t\f ]+$//mg;
 
@@ -962,7 +981,7 @@ Left and right padding with any character, modifying C<$text> directly:
 
 (contributed by brian d foy)
 
-If you know where the columns that contain the data, you can
+If you know the columns that contain the data, you can
 use C<substr> to extract a single column.
 
        my $column = substr( $line, $start_column, $length );
@@ -981,11 +1000,11 @@ appear as part of the data.
 
 If you want to work with comma-separated values, don't do this since
 that format is a bit more complicated. Use one of the modules that
-handle that fornat, such as C<Text::CSV>, C<Text::CSV_XS>, or
+handle that format, such as C<Text::CSV>, C<Text::CSV_XS>, or
 C<Text::CSV_PP>.
 
 If you want to break apart an entire line of fixed columns, you can use
-C<unpack> with the A (ASCII) format. by using a number after the format
+C<unpack> with the A (ASCII) format. By using a number after the format
 specifier, you can denote the column width. See the C<pack> and C<unpack>
 entries in L<perlfunc> for more details.
 
@@ -1007,12 +1026,15 @@ C<Text::Metaphone>, and C<Text::DoubleMetaphone> modules.
 (contributed by brian d foy)
 
 If you can avoid it, don't, or if you can use a templating system,
-such as C<Text::Template> or C<Template> Toolkit, do that instead.
+such as C<Text::Template> or C<Template> Toolkit, do that instead. You
+might even be able to get the job done with C<sprintf> or C<printf>:
+
+       my $string = sprintf 'Say hello to %s and %s', $foo, $bar;
 
 However, for the one-off simple case where I don't want to pull out a
 full templating system, I'll use a string that has two Perl scalar
 variables in it. In this example, I want to expand C<$foo> and C<$bar>
-to their variable's values.
+to their variable's values:
 
        my $foo = 'Fred';
        my $bar = 'Barney';
@@ -1022,20 +1044,25 @@ One way I can do this involves the substitution operator and a double
 C</e> flag.  The first C</e> evaluates C<$1> on the replacement side and
 turns it into C<$foo>. The second /e starts with C<$foo> and replaces
 it with its value. C<$foo>, then, turns into 'Fred', and that's finally
-what's left in the string.
+what's left in the string:
 
        $string =~ s/(\$\w+)/$1/eeg; # 'Say hello to Fred and Barney'
 
 The C</e> will also silently ignore violations of strict, replacing
-undefined variable names with the empty string.
-
-I could also pull the values from a hash instead of evaluating 
-variable names. Using a single C</e>, I can check the hash to ensure
-the value exists, and if it doesn't, I can replace the missing value
-with a marker, in this case C<???> to signal that I missed something:
+undefined variable names with the empty string. Since I'm using the
+C</e> flag (twice even!), I have all of the same security problems I
+have with C<eval> in its string form. If there's something odd in
+C<$foo>, perhaps something like C<@{[ system "rm -rf /" ]}>, then
+I could get myself in trouble.
+
+To get around the security problem, I could also pull the values from
+a hash instead of evaluating variable names. Using a single C</e>, I
+can check the hash to ensure the value exists, and if it doesn't, I
+can replace the missing value with a marker, in this case C<???> to
+signal that I missed something:
 
        my $string = 'This has $foo and $bar';
-       
+
        my %Replacements = (
                foo  => 'Fred',
                );
@@ -1134,7 +1161,7 @@ subsequent line.
     sub fix {
         local $_ = shift;
         my ($white, $leader);  # common whitespace and common leading string
-        if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\1\2?.*\n)+$/) {
+        if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\g1\g2?.*\n)+$/) {
             ($white, $leader) = ($2, quotemeta($1));
         } else {
             ($white, $leader) = (/^(\s+)/, '');
@@ -1173,43 +1200,115 @@ indentation correctly preserved:
 
 =head2 What is the difference between a list and an array?
 
-An array has a changeable length.  A list does not.  An array is
-something you can push or pop, while a list is a set of values.  Some
-people make the distinction that a list is a value while an array is a
-variable. Subroutines are passed and return lists, you put things into
-list context, you initialize arrays with lists, and you C<foreach()>
-across a list.  C<@> variables are arrays, anonymous arrays are
-arrays, arrays in scalar context behave like the number of elements in
-them, subroutines access their arguments through the array C<@_>, and
-C<push>/C<pop>/C<shift> only work on arrays.
+(contributed by brian d foy)
+
+A list is a fixed collection of scalars. An array is a variable that
+holds a variable collection of scalars. An array can supply its collection
+for list operations, so list operations also work on arrays:
+
+       # slices
+       ( 'dog', 'cat', 'bird' )[2,3];
+       @animals[2,3];
 
-As a side note, there's no such thing as a list in scalar context.
-When you say
+       # iteration
+       foreach ( qw( dog cat bird ) ) { ... }
+       foreach ( @animals ) { ... }
 
-       $scalar = (2, 5, 7, 9);
+       my @three = grep { length == 3 } qw( dog cat bird );
+       my @three = grep { length == 3 } @animals;
 
-you're using the comma operator in scalar context, so it uses the scalar
-comma operator.  There never was a list there at all! This causes the
-last value to be returned: 9.
+       # supply an argument list
+       wash_animals( qw( dog cat bird ) );
+       wash_animals( @animals );
+
+Array operations, which change the scalars, rearranges them, or adds
+or subtracts some scalars, only work on arrays. These can't work on a
+list, which is fixed. Array operations include C<shift>, C<unshift>,
+C<push>, C<pop>, and C<splice>.
+
+An array can also change its length:
+
+       $#animals = 1;  # truncate to two elements
+       $#animals = 10000; # pre-extend to 10,001 elements
+
+You can change an array element, but you can't change a list element:
+
+       $animals[0] = 'Rottweiler';
+       qw( dog cat bird )[0] = 'Rottweiler'; # syntax error!
+
+       foreach ( @animals ) {
+               s/^d/fr/;  # works fine
+               }
+
+       foreach ( qw( dog cat bird ) ) {
+               s/^d/fr/;  # Error! Modification of read only value!
+               }
+
+However, if the list element is itself a variable, it appears that you
+can change a list element. However, the list element is the variable, not
+the data. You're not changing the list element, but something the list
+element refers to. The list element itself doesn't change: it's still
+the same variable.
+
+You also have to be careful about context. You can assign an array to
+a scalar to get the number of elements in the array. This only works
+for arrays, though:
+
+       my $count = @animals;  # only works with arrays
+
+If you try to do the same thing with what you think is a list, you
+get a quite different result. Although it looks like you have a list
+on the righthand side, Perl actually sees a bunch of scalars separated
+by a comma:
+
+       my $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird
+
+Since you're assigning to a scalar, the righthand side is in scalar
+context. The comma operator (yes, it's an operator!) in scalar
+context evaluates its lefthand side, throws away the result, and
+evaluates it's righthand side and returns the result. In effect,
+that list-lookalike assigns to C<$scalar> it's rightmost value. Many
+people mess this up because they choose a list-lookalike whose
+last element is also the count they expect:
+
+       my $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally
 
 =head2 What is the difference between $array[1] and @array[1]?
 
-The former is a scalar value; the latter an array slice, making
-it a list with one (scalar) value.  You should use $ when you want a
-scalar value (most of the time) and @ when you want a list with one
-scalar value in it (very, very rarely; nearly never, in fact).
+(contributed by brian d foy)
+
+The difference is the sigil, that special character in front of the
+array name. The C<$> sigil means "exactly one item", while the C<@>
+sigil means "zero or more items". The C<$> gets you a single scalar,
+while the C<@> gets you a list.
+
+The confusion arises because people incorrectly assume that the sigil
+denotes the variable type.
+
+The C<$array[1]> is a single-element access to the array. It's going
+to return the item in index 1 (or undef if there is no item there).
+If you intend to get exactly one element from the array, this is the
+form you should use.
 
-Sometimes it doesn't make a difference, but sometimes it does.
-For example, compare:
+The C<@array[1]> is an array slice, although it has only one index.
+You can pull out multiple elements simultaneously by specifying
+additional indices as a list, like C<@array[1,4,3,0]>.
 
-       $good[0] = `some program that outputs several lines`;
+Using a slice on the lefthand side of the assignment supplies list
+context to the righthand side. This can lead to unexpected results.
+For instance, if you want to read a single line from a filehandle,
+assigning to a scalar value is fine:
 
-with
+       $array[1] = <STDIN>;
 
-       @bad[0]  = `same program that outputs several lines`;
+However, in list context, the line input operator returns all of the
+lines as a list. The first line goes into C<@array[1]> and the rest
+of the lines mysteriously disappear:
 
-The C<use warnings> pragma and the B<-w> flag will warn you about these
-matters.
+       @array[1] = <STDIN>;  # most likely not what you want
+
+Either the C<use warnings> pragma or the B<-w> flag will warn you when
+you use an array slice with a single index.
 
 =head2 How can I remove duplicate elements from a list or array?
 
@@ -1266,16 +1365,32 @@ same thing.
 
 =head2 How can I tell whether a certain element is contained in a list or array?
 
-(portions of this answer contributed by Anno Siegel)
+(portions of this answer contributed by Anno Siegel and brian d foy)
 
 Hearing the word "in" is an I<in>dication that you probably should have
 used a hash, not a list or array, to store your data.  Hashes are
 designed to answer this question quickly and efficiently.  Arrays aren't.
 
-That being said, there are several ways to approach this.  If you
+That being said, there are several ways to approach this.  In Perl 5.10
+and later, you can use the smart match operator to check that an item is
+contained in an array or a hash:
+
+       use 5.010;
+
+       if( $item ~~ @array )
+               {
+               say "The array contains $item"
+               }
+
+       if( $item ~~ %hash )
+               {
+               say "The hash contains $item"
+               }
+
+With earlier versions of Perl, you have to do a bit more work. If you
 are going to make this query many times over arbitrary string values,
 the fastest way is probably to invert the original array and maintain a
-hash whose keys are the first array's values.
+hash whose keys are the first array's values:
 
        @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
        %is_blue = ();
@@ -1309,7 +1424,7 @@ multiple values against the same array.
 
 If you are testing only once, the standard module C<List::Util> exports
 the function C<first> for this purpose.  It works by stopping once it
-finds the element. It's written in C for speed, and its Perl equivalant
+finds the element. It's written in C for speed, and its Perl equivalent
 looks like this subroutine:
 
        sub first (&@) {
@@ -1350,6 +1465,21 @@ in either A or in B but not in both.  Think of it as an xor operation.
 
 =head2 How do I test whether two arrays or hashes are equal?
 
+With Perl 5.10 and later, the smart match operator can give you the answer
+with the least amount of work:
+
+       use 5.010;
+
+       if( @array1 ~~ @array2 )
+               {
+               say "The arrays are the same";
+               }
+
+       if( %hash1 ~~ %hash2 ) # doesn't check values!
+               {
+               say "The hash keys are the same";
+               }
+
 The following code works for single-level arrays.  It uses a
 stringwise comparison, and does not distinguish defined versus
 undefined empty strings.  Modify if you have other needs.
@@ -1431,63 +1561,43 @@ that satisfies the condition.
 
 =head2 How do I handle linked lists?
 
-In general, you usually don't need a linked list in Perl, since with
-regular arrays, you can push and pop or shift and unshift at either
-end, or you can use splice to add and/or remove arbitrary number of
-elements at arbitrary points.  Both pop and shift are both O(1)
-operations on Perl's dynamic arrays.  In the absence of shifts and
-pops, push in general needs to reallocate on the order every log(N)
-times, and unshift will need to copy pointers each time.
-
-If you really, really wanted, you could use structures as described in
-L<perldsc> or L<perltoot> and do just what the algorithm book tells
-you to do.  For example, imagine a list node like this:
-
-       $node = {
-               VALUE => 42,
-               LINK  => undef,
-               };
-
-You could walk the list this way:
+(contributed by brian d foy)
 
-       print "List: ";
-       for ($node = $head;  $node; $node = $node->{LINK}) {
-               print $node->{VALUE}, " ";
-               }
-       print "\n";
+Perl's arrays do not have a fixed size, so you don't need linked lists
+if you just want to add or remove items. You can use array operations
+such as C<push>, C<pop>, C<shift>, C<unshift>, or C<splice> to do
+that.
 
-You could add to the list this way:
+Sometimes, however, linked lists can be useful in situations where you
+want to "shard" an array so you have have many small arrays instead of
+a single big array. You can keep arrays longer than Perl's largest
+array index, lock smaller arrays separately in threaded programs,
+reallocate less memory, or quickly insert elements in the middle of
+the chain.
 
-       my ($head, $tail);
-       $tail = append($head, 1);       # grow a new head
-       for $value ( 2 .. 10 ) {
-               $tail = append($tail, $value);
-               }
+Steve Lembark goes through the details in his YAPC::NA 2009 talk "Perly
+Linked Lists" ( http://www.slideshare.net/lembark/perly-linked-lists ),
+although you can just use his C<LinkedList::Single> module.
 
-       sub append {
-               my($list, $value) = @_;
-               my $node = { VALUE => $value };
-               if ($list) {
-                       $node->{LINK} = $list->{LINK};
-                       $list->{LINK} = $node;
-                       }
-               else {
-                       $_[0] = $node;      # replace caller's version
-                       }
-               return $node;
-               }
+=head2 How do I handle circular lists?
+X<circular> X<array> X<Tie::Cycle> X<Array::Iterator::Circular>
+X<cycle> X<modulus>
 
-But again, Perl's built-in are virtually always good enough.
+(contributed by brian d foy)
 
-=head2 How do I handle circular lists?
+If you want to cycle through an array endlessly, you can increment the
+index modulo the number of elements in the array:
 
-Circular lists could be handled in the traditional fashion with linked
-lists, or you could just do something like this with an array:
+       my @array = qw( a b c );
+       my $i = 0;
 
-       unshift(@array, pop(@array));  # the last shall be first
-       push(@array, shift(@array));   # and vice versa
+       while( 1 ) {
+               print $array[ $i++ % @array ], "\n";
+               last if $i > 20;
+               }
 
-You can also use C<Tie::Cycle>:
+You can also use C<Tie::Cycle> to use a scalar that always has the
+next element of the circular array:
 
        use Tie::Cycle;
 
@@ -1497,6 +1607,19 @@ You can also use C<Tie::Cycle>:
        print $cycle; # 000000
        print $cycle; # FFFF00
 
+The C<Array::Iterator::Circular> creates an iterator object for
+circular arrays:
+
+       use Array::Iterator::Circular;
+
+       my $color_iterator = Array::Iterator::Circular->new(
+               qw(red green blue orange)
+               );
+
+       foreach ( 1 .. 20 ) {
+               print $color_iterator->next, "\n";
+               }
+
 =head2 How do I shuffle an array randomly?
 
 If you either have Perl 5.8.0 or later installed, or if you have
@@ -1510,6 +1633,8 @@ If not, you can use a Fisher-Yates shuffle.
 
        sub fisher_yates_shuffle {
                my $deck = shift;  # $deck is a reference to an array
+               return unless @$deck; # must not be empty!
+
                my $i = @$deck;
                while (--$i) {
                        my $j = int rand ($i+1);
@@ -1589,14 +1714,18 @@ Or, simply:
        my $element = $array[ rand @array ];
 
 =head2 How do I permute N elements of a list?
+X<List::Permutor> X<permute> X<Algorithm::Loops> X<Knuth>
+X<The Art of Computer Programming> X<Fischer-Krause>
 
-Use the C<List::Permutor> module on CPAN.  If the list is actually an
+Use the C<List::Permutor> module on CPAN. If the list is actually an
 array, try the C<Algorithm::Permute> module (also on CPAN). It's
-written in XS code and is very efficient.
+written in XS code and is very efficient:
 
        use Algorithm::Permute;
+
        my @array = 'a'..'d';
        my $p_iterator = Algorithm::Permute->new ( \@array );
+
        while (my @perm = $p_iterator->next) {
           print "next permutation: (@perm)\n";
                }
@@ -1604,19 +1733,20 @@ written in XS code and is very efficient.
 For even faster execution, you could do:
 
        use Algorithm::Permute;
+
        my @array = 'a'..'d';
+
        Algorithm::Permute::permute {
                print "next permutation: (@array)\n";
                } @array;
 
-Here's a little program that generates all permutations of
-all the words on each line of input. The algorithm embodied
-in the C<permute()> function is discussed in Volume 4 (still
-unpublished) of Knuth's I<The Art of Computer Programming>
-and will work on any list:
+Here's a little program that generates all permutations of all the
+words on each line of input. The algorithm embodied in the
+C<permute()> function is discussed in Volume 4 (still unpublished) of
+Knuth's I<The Art of Computer Programming> and will work on any list:
 
        #!/usr/bin/perl -n
-       # Fischer-Kause ordered permutation generator
+       # Fischer-Krause ordered permutation generator
 
        sub permute (&@) {
                my $code = shift;
@@ -1631,7 +1761,22 @@ and will work on any list:
                }
        }
 
-       permute {print"@_\n"} split;
+       permute { print "@_\n" } split;
+
+The C<Algorithm::Loops> module also provides the C<NextPermute> and
+C<NextPermuteNum> functions which efficiently find all unique permutations
+of an array, even if it contains duplicate values, modifying it in-place:
+if its elements are in reverse-sorted order then the array is reversed,
+making it sorted, and it returns false; otherwise the next
+permutation is returned.
+
+C<NextPermute> uses string order and C<NextPermuteNum> numeric order, so
+you can enumerate all the permutations of C<0..9> like this:
+
+       use Algorithm::Loops qw(NextPermuteNum);
+
+    my @list= 0..9;
+    do { print "@list\n" } while NextPermuteNum @list;
 
 =head2 How do I sort an array by (anything)?
 
@@ -1686,14 +1831,23 @@ See also the question later in L<perlfaq4> on sorting hashes.
 Use C<pack()> and C<unpack()>, or else C<vec()> and the bitwise
 operations.
 
-For example, this sets C<$vec> to have bit N set if C<$ints[N]> was
-set:
+For example, you don't have to store individual bits in an array
+(which would mean that you're wasting a lot of space). To convert an
+array of bits to a string, use C<vec()> to set the right bits. This
+sets C<$vec> to have bit N set only if C<$ints[N]> was set:
 
+       @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... )
        $vec = '';
-       foreach(@ints) { vec($vec,$_,1) = 1 }
+       foreach( 0 .. $#ints ) {
+               vec($vec,$_,1) = 1 if $ints[$_];
+               }
+
+The string C<$vec> only takes up as many bits as it needs. For
+instance, if you had 16 entries in C<@ints>, C<$vec> only needs two
+bytes to store them (not counting the scalar variable overhead).
 
-Here's how, given a vector in C<$vec>, you can get those bits into your
-C<@ints> array:
+Here's how, given a vector in C<$vec>, you can get those bits into
+your C<@ints> array:
 
        sub bitvec_to_list {
                my $vec = shift;
@@ -1799,15 +1953,113 @@ in the 5.004 release or later of Perl for more detail.
 
 =head2 How do I process an entire hash?
 
-Use the each() function (see L<perlfunc/each>) if you don't care
-whether it's sorted:
+(contributed by brian d foy)
+
+There are a couple of ways that you can process an entire hash. You
+can get a list of keys, then go through each key, or grab a one
+key-value pair at a time.
+
+To go through all of the keys, use the C<keys> function. This extracts
+all of the keys of the hash and gives them back to you as a list. You
+can then get the value through the particular key you're processing:
+
+       foreach my $key ( keys %hash ) {
+               my $value = $hash{$key}
+               ...
+               }
+
+Once you have the list of keys, you can process that list before you
+process the hash elements. For instance, you can sort the keys so you
+can process them in lexical order:
+
+       foreach my $key ( sort keys %hash ) {
+               my $value = $hash{$key}
+               ...
+               }
+
+Or, you might want to only process some of the items. If you only want
+to deal with the keys that start with C<text:>, you can select just
+those using C<grep>:
 
-       while ( ($key, $value) = each %hash) {
-               print "$key = $value\n";
+       foreach my $key ( grep /^text:/, keys %hash ) {
+               my $value = $hash{$key}
+               ...
                }
 
-If you want it sorted, you'll have to use foreach() on the result of
-sorting the keys as shown in an earlier question.
+If the hash is very large, you might not want to create a long list of
+keys. To save some memory, you can grab one key-value pair at a time using
+C<each()>, which returns a pair you haven't seen yet:
+
+       while( my( $key, $value ) = each( %hash ) ) {
+               ...
+               }
+
+The C<each> operator returns the pairs in apparently random order, so if
+ordering matters to you, you'll have to stick with the C<keys> method.
+
+The C<each()> operator can be a bit tricky though. You can't add or
+delete keys of the hash while you're using it without possibly
+skipping or re-processing some pairs after Perl internally rehashes
+all of the elements. Additionally, a hash has only one iterator, so if
+you use C<keys>, C<values>, or C<each> on the same hash, you can reset
+the iterator and mess up your processing. See the C<each> entry in
+L<perlfunc> for more details.
+
+=head2 How do I merge two hashes?
+X<hash> X<merge> X<slice, hash>
+
+(contributed by brian d foy)
+
+Before you decide to merge two hashes, you have to decide what to do
+if both hashes contain keys that are the same and if you want to leave
+the original hashes as they were.
+
+If you want to preserve the original hashes, copy one hash (C<%hash1>)
+to a new hash (C<%new_hash>), then add the keys from the other hash
+(C<%hash2> to the new hash. Checking that the key already exists in
+C<%new_hash> gives you a chance to decide what to do with the
+duplicates:
+
+       my %new_hash = %hash1; # make a copy; leave %hash1 alone
+
+       foreach my $key2 ( keys %hash2 )
+               {
+               if( exists $new_hash{$key2} )
+                       {
+                       warn "Key [$key2] is in both hashes!";
+                       # handle the duplicate (perhaps only warning)
+                       ...
+                       next;
+                       }
+               else
+                       {
+                       $new_hash{$key2} = $hash2{$key2};
+                       }
+               }
+
+If you don't want to create a new hash, you can still use this looping
+technique; just change the C<%new_hash> to C<%hash1>.
+
+       foreach my $key2 ( keys %hash2 )
+               {
+               if( exists $hash1{$key2} )
+                       {
+                       warn "Key [$key2] is in both hashes!";
+                       # handle the duplicate (perhaps only warning)
+                       ...
+                       next;
+                       }
+               else
+                       {
+                       $hash1{$key2} = $hash2{$key2};
+                       }
+               }
+
+If you don't care that one hash overwrites keys and values from the other, you
+could just use a hash slice to add one hash to another. In this case, values
+from C<%hash2> replace values from C<%hash1> when they have keys in common:
+
+       @hash1{ keys %hash2 } = values %hash2;
 
 =head2 What happens if I add or remove keys from a hash while iterating over it?
 
@@ -1845,14 +2097,35 @@ worry you, you can always reverse the hash into a hash of arrays instead:
 
 =head2 How can I know how many entries are in a hash?
 
-If you mean how many keys, then all you have to do is
-use the keys() function in a scalar context:
+(contributed by brian d foy)
+
+This is very similar to "How do I process an entire hash?", also in
+L<perlfaq4>, but a bit simpler in the common cases.
 
-    $num_keys = keys %hash;
+You can use the C<keys()> built-in function in scalar context to find out
+have many entries you have in a hash:
 
-The keys() function also resets the iterator, which means that you may
+       my $key_count = keys %hash; # must be scalar context!
+
+If you want to find out how many entries have a defined value, that's
+a bit different. You have to check each value. A C<grep> is handy:
+
+       my $defined_value_count = grep { defined } values %hash;
+
+You can use that same structure to count the entries any way that
+you like. If you want the count of the keys with vowels in them,
+you just test for that instead:
+
+       my $vowel_count = grep { /[aeiou]/ } keys %hash;
+
+The C<grep> in scalar context returns the count. If you want the list
+of matching items, just use it in list context instead:
+
+       my @defined_values = grep { defined } values %hash;
+
+The C<keys()> function also resets the iterator, which means that you may
 see strange results if you use this between uses of other hash operators
-such as each().
+such as C<each()>.
 
 =head2 How do I sort a hash (optionally by value instead of key)?
 
@@ -1868,7 +2141,7 @@ create a report which lists the keys in ASCIIbetical order.
 
        foreach my $key ( @keys )
                {
-               printf "%-20s %6d\n", $key, $hash{$value};
+               printf "%-20s %6d\n", $key, $hash{$key};
                }
 
 We could get more fancy in the C<sort()> block though. Instead of
@@ -1923,7 +2196,7 @@ C<$hash{$key}> will be C<undef> while C<exists $hash{$key}>
 will return true.  This corresponds to (C<$key>, C<undef>)
 being in the hash.
 
-Pictures help...  here's the C<%hash> table:
+Pictures help...  Here's the C<%hash> table:
 
          keys  values
        +------+------+
@@ -1939,7 +2212,7 @@ And these conditions hold
        $hash{'d'}                       is false
        defined $hash{'d'}               is true
        defined $hash{'a'}               is true
-       exists $hash{'a'}                is true (Perl5 only)
+       exists $hash{'a'}                is true (Perl 5 only)
        grep ($_ eq 'a', keys %hash)     is true
 
 If you now say
@@ -1963,7 +2236,7 @@ and these conditions now hold; changes in caps:
        $hash{'d'}                       is false
        defined $hash{'d'}               is true
        defined $hash{'a'}               is FALSE
-       exists $hash{'a'}                is true (Perl5 only)
+       exists $hash{'a'}                is true (Perl 5 only)
        grep ($_ eq 'a', keys %hash)     is true
 
 Notice the last two: you have an undef value, but a defined key!
@@ -1987,7 +2260,7 @@ and these conditions now hold; changes in caps:
        $hash{'d'}                       is false
        defined $hash{'d'}               is true
        defined $hash{'a'}               is false
-       exists $hash{'a'}                is FALSE (Perl5 only)
+       exists $hash{'a'}                is FALSE (Perl 5 only)
        grep ($_ eq 'a', keys %hash)     is FALSE
 
 See, the whole entry is gone!
@@ -2002,10 +2275,16 @@ end up doing is not what they do with ordinary hashes.
 
 =head2 How do I reset an each() operation part-way through?
 
-Using C<keys %hash> in scalar context returns the number of keys in
-the hash I<and> resets the iterator associated with the hash.  You may
-need to do this if you use C<last> to exit a loop early so that when
-you re-enter it, the hash iterator has been reset.
+(contributed by brian d foy)
+
+You can use the C<keys> or C<values> functions to reset C<each>. To
+simply reset the iterator used by C<each> without doing anything else,
+use one of them in void context:
+
+       keys %hash; # resets iterator, nothing else.
+       values %hash; # resets iterator, nothing else.
+
+See the documentation for C<each> in L<perlfunc>.
 
 =head2 How can I get the unique keys from two hashes?
 
@@ -2056,20 +2335,44 @@ Use the C<Tie::IxHash> from CPAN.
 
 =head2 Why does passing a subroutine an undefined element in a hash create it?
 
-If you say something like:
+(contributed by brian d foy)
+
+Are you using a really old version of Perl?
 
-       somefunc($hash{"nonesuch key here"});
+Normally, accessing a hash key's value for a nonexistent key will
+I<not> create the key.
 
-Then that element "autovivifies"; that is, it springs into existence
-whether you store something there or not.  That's because functions
-get scalars passed in by reference.  If somefunc() modifies C<$_[0]>,
-it has to be ready to write it back into the caller's version.
+       my %hash  = ();
+       my $value = $hash{ 'foo' };
+       print "This won't print\n" if exists $hash{ 'foo' };
 
-This has been fixed as of Perl5.004.
+Passing C<$hash{ 'foo' }> to a subroutine used to be a special case, though.
+Since you could assign directly to C<$_[0]>, Perl had to be ready to
+make that assignment so it created the hash key ahead of time:
 
-Normally, merely accessing a key's value for a nonexistent key does
-I<not> cause that key to be forever there.  This is different than
-awk's behavior.
+    my_sub( $hash{ 'foo' } );
+       print "This will print before 5.004\n" if exists $hash{ 'foo' };
+
+       sub my_sub {
+               # $_[0] = 'bar'; # create hash key in case you do this
+               1;
+               }
+
+Since Perl 5.004, however, this situation is a special case and Perl
+creates the hash key only when you make the assignment:
+
+    my_sub( $hash{ 'foo' } );
+       print "This will print, even after 5.004\n" if exists $hash{ 'foo' };
+
+       sub my_sub {
+               $_[0] = 'bar';
+               }
+
+However, if you want the old behavior (and think carefully about that
+because it's a weird side effect), you can pass a hash slice instead.
+Perl 5.004 didn't make this a special case:
+
+       my_sub( @hash{ qw/foo/ } );
 
 =head2 How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?
 
@@ -2084,25 +2387,106 @@ Usually a hash ref, perhaps like this:
                PALS   => [ "Norbert", "Rhys", "Phineas"],
        };
 
-References are documented in L<perlref> and the upcoming L<perlreftut>.
+References are documented in L<perlref> and L<perlreftut>.
 Examples of complex data structures are given in L<perldsc> and
 L<perllol>.  Examples of structures and object-oriented classes are
 in L<perltoot>.
 
 =head2 How can I use a reference as a hash key?
 
-(contributed by brian d foy)
+(contributed by brian d foy and Ben Morrow)
 
 Hash keys are strings, so you can't really use a reference as the key.
 When you try to do that, perl turns the reference into its stringified
 form (for instance, C<HASH(0xDEADBEEF)>). From there you can't get
 back the reference from the stringified form, at least without doing
-some extra work on your own. Also remember that hash keys must be
-unique, but two different variables can store the same reference (and
-those variables can change later).
+some extra work on your own.
+
+Remember that the entry in the hash will still be there even if
+the referenced variable  goes out of scope, and that it is entirely
+possible for Perl to subsequently allocate a different variable at
+the same address. This will mean a new variable might accidentally
+be associated with the value for an old.
+
+If you have Perl 5.10 or later, and you just want to store a value
+against the reference for lookup later, you can use the core
+Hash::Util::Fieldhash module. This will also handle renaming the
+keys if you use multiple threads (which causes all variables to be
+reallocated at new addresses, changing their stringification), and
+garbage-collecting the entries when the referenced variable goes out
+of scope.
+
+If you actually need to be able to get a real reference back from
+each hash entry, you can use the Tie::RefHash module, which does the
+required work for you.
 
-The C<Tie::RefHash> module, which is distributed with perl, might be
-what you want. It handles that extra work.
+=head2 How can I check if a key exists in a multilevel hash?
+
+(contributed by brian d foy)
+
+The trick to this problem is avoiding accidental autovivification. If 
+you want to check three keys deep, you might naïvely try this:
+
+       my %hash;
+       if( exists $hash{key1}{key2}{key3} ) {
+               ...;
+               }
+
+Even though you started with a completely empty hash, after that call to 
+C<exists> you've created the structure you needed to check for C<key3>:
+
+       %hash = (
+                         'key1' => {
+                                                 'key2' => {}
+                                               }
+                       );
+
+That's autovivification. You can get around this in a few ways. The
+easiest way is to just turn it off. The lexical C<autovivification>
+pragma is available on CPAN. Now you don't add to the hash:
+
+       {
+       no autovivification;
+       my %hash;
+       if( exists $hash{key1}{key2}{key3} ) {
+               ...;
+               }
+       }
+
+The C<Data::Diver> module on CPAN can do it for you too. Its C<Dive>
+subroutine can tell you not only if the keys exist but also get the
+value:
+
+       use Data::Diver qw(Dive);
+       
+    my @exists = Dive( \%hash, qw(key1 key2 key3) );
+    if(  ! @exists  ) {
+        ...; # keys do not exist
+       } 
+    elsif(  ! defined $exists[0]  ) {
+        ...; # keys exist but value is undef
+       }
+
+You can easily do this yourself too by checking each level of the hash
+before you move onto the next level. This is essentially what
+C<Data::Diver> does for you:
+
+       if( check_hash( \%hash, qw(key1 key2 key3) ) ) {
+               ...;
+               }
+       
+       sub check_hash {
+          my( $hash, @keys ) = @_;
+       
+          return unless @keys;
+       
+          foreach my $key ( @keys ) {
+                  return unless eval { exists $hash->{$key} };
+                  $hash = $hash->{$key};
+                  }
+       
+          return 1;
+          }
 
 =head1 Data: Misc
 
@@ -2122,31 +2506,39 @@ some gotchas.  See the section on Regular Expressions.
 =head2 How do I determine whether a scalar is a number/whole/integer/float?
 
 Assuming that you don't care about IEEE notations like "NaN" or
-"Infinity", you probably just want to use a regular expression.
+"Infinity", you probably just want to use a regular expression:
 
-       if (/\D/)            { print "has nondigits\n" }
-       if (/^\d+$/)         { print "is a whole number\n" }
-       if (/^-?\d+$/)       { print "is an integer\n" }
-       if (/^[+-]?\d+$/)    { print "is a +/- integer\n" }
-       if (/^-?\d+\.?\d*$/) { print "is a real number\n" }
-       if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print "is a decimal number\n" }
-       if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
-                       { print "a C float\n" }
+       use 5.010;
+       
+       given( $number ) {
+               when( /\D/ )             
+                       { say "\thas nondigits"; continue }
+               when( /^\d+\z/ )         
+                       { say "\tis a whole number"; continue }
+               when( /^-?\d+\z/ )       
+                       { say "\tis an integer"; continue }
+               when( /^[+-]?\d+\z/ )    
+                       { say "\tis a +/- integer"; continue }
+               when( /^-?(?:\d+\.?|\.\d)\d*\z/ ) 
+                       { say "\tis a real number"; continue }
+               when( /^[+-]?(?=\.?\d)\d*\.?\d*(?:e[+-]?\d+)?\z/i)
+                       { say "\tis a C float" }
+               }
 
 There are also some commonly used modules for the task.
 L<Scalar::Util> (distributed with 5.8) provides access to perl's
 internal function C<looks_like_number> for determining whether a
-variable looks like a number.  L<Data::Types> exports functions that
+variable looks like a number. L<Data::Types> exports functions that
 validate data types using both the above and other regular
 expressions. Thirdly, there is C<Regexp::Common> which has regular
 expressions to match various types of numbers. Those three modules are
 available from the CPAN.
 
 If you're on a POSIX system, Perl supports the C<POSIX::strtod>
-function.  Its semantics are somewhat cumbersome, so here's a
-C<getnum> wrapper function for more convenient access.  This function
+function. Its semantics are somewhat cumbersome, so here's a
+C<getnum> wrapper function for more convenient access. This function
 takes a string and returns the number it found, or C<undef> for input
-that isn't a C float.  The C<is_numeric> function is a front end to
+that isn't a C float. The C<is_numeric> function is a front end to
 C<getnum> if you just want to say, "Is this a float?"
 
        sub getnum {
@@ -2205,7 +2597,14 @@ you wanted to copy.
 
 =head2 How do I define methods for every class/object?
 
-Use the C<UNIVERSAL> class (see L<UNIVERSAL>).
+(contributed by Ben Morrow)
+
+You can use the C<UNIVERSAL> class (see L<UNIVERSAL>). However, please
+be very careful to consider the consequences of doing this: adding
+methods to every object is very likely to have unintended
+consequences. If possible, it would be better to have all your object
+inherit from some common base class, or to use an object system like
+Moose that supports roles.
 
 =head2 How do I verify a credit card checksum?
 
@@ -2213,21 +2612,15 @@ Get the C<Business::CreditCard> module from CPAN.
 
 =head2 How do I pack arrays of doubles or floats for XS code?
 
-The kgbpack.c code in the C<PGPLOT> module on CPAN does just this.
+The arrays.h/arrays.c code in the C<PGPLOT> module on CPAN does just this.
 If you're doing a lot of float or double processing, consider using
 the C<PDL> module from CPAN instead--it makes number-crunching easy.
 
-=head1 REVISION
-
-Revision: $Revision: 7996 $
-
-Date: $Date: 2006-11-01 09:24:38 +0100 (mer, 01 nov 2006) $
-
-See L<perlfaq> for source control details and availability.
+See L<http://search.cpan.org/dist/PGPLOT> for the code.
 
 =head1 AUTHOR AND COPYRIGHT
 
-Copyright (c) 1997-2006 Tom Christiansen, Nathan Torkington, and
+Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and
 other authors as noted. All rights reserved.
 
 This documentation is free; you can redistribute it and/or modify it