mplaints
\&        return 0 unless @$first == @$second;
\&        for (my $i = 0; $i < @$first; $i++) {
\&            return 0 if $first->[$i] ne $second->[$i];
\&        }
\&        return 1;
\&    }
.Ve
.PP
For multilevel structures, you may wish to use an approach more
like this one.  It uses the \s-1CPAN\s0 module FreezeThaw:
.PP
.Vb 2
\&    use FreezeThaw qw(cmpStr);
\&    @a = @b = ( "this", "that", [ "more", "stuff" ] );
.Ve
.PP
.Vb 4
\&    printf "a and b contain %s arrays\en",
\&        cmpStr(\e@a, \e@b) == 0
\&            ? "the same"
\&            : "different";
.Ve
.PP
This approach also works for comparing hashes.  Here
we'll demonstrate two different answers:
.PP
.Vb 1
\&    use FreezeThaw qw(cmpStr cmpStrHard);
.Ve
.PP
.Vb 3
\&    %a = %b = ( "this" => "that", "extra" => [ "more", "stuff" ] );
\&    $a{EXTRA} = \e%b;
\&    $b{EXTRA} = \e%a;
.Ve
.PP
.Vb 2
\&    printf "a and b contain %s hashes\en",
\&        cmpStr(\e%a, \e%b) == 0 ? "the same" : "different";
.Ve
.PP
.Vb 2
\&    printf "a and b contain %s hashes\en",
\&        cmpStrHard(\e%a, \e%b) == 0 ? "the same" : "different";
.Ve
.PP
The first reports that both those the hashes contain the same data,
while the second reports that they do not.  Which you prefer is left as
an exercise to the reader.
.Sh "How do I find the first array element for which a condition is true?"
.IX Subsection "How do I find the first array element for which a condition is true?"
To find the first array element which satisfies a condition, you can
use the \fIfirst()\fR function in the List::Util module, which comes with
Perl 5.8.  This example finds the first element that contains \*(L"Perl\*(R".
.PP
.Vb 1
\&        use List::Util qw(first);
.Ve
.PP
.Vb 1
\&        my $element = first { /Perl/ } @array;
.Ve
.PP
If you cannot use List::Util, you can make your own loop to do the
same thing.  Once you find the element, you stop the loop with last.
.PP
.Vb 5
\&        my $found;
\&        foreach ( @array )
\&                {
\&                if( /Perl/ ) { $found = $_; last }
\&                }
.Ve
.PP
If you want the array index, you can iterate through the indices
and check the array element at each index until you find one
that satisfies the condition.
.PP
.Vb 10
\&        my( $found, $index ) = ( undef, -1 );
\&        for( $i = 0; $i < @array; $i++ )
\&                {
\&                if( $array[$i] =~ /Perl/ )
\&                        {
\&                        $found = $array[$i];
\&                        $index = $i;
\&                        last;
\&                        }
\&                }
.Ve
.Sh "How do I handle linked lists?"
.IX Subsection "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.
.PP
If you really, really wanted, you could use structures as described in
perldsc or perltoot and do just what the algorithm book tells you
to do.  For example, imagine a list node like this:
.PP
.Vb 4
\&    $node = {
\&        VALUE => 42,
\&        LINK  => undef,
\&    };
.Ve
.PP
You could walk the list this way:
.PP
.Vb 5
\&    print "List: ";
\&    for ($node = $head;  $node; $node = $node->{LINK}) {
\&        print $node->{VALUE}, " ";
\&    }
\&    print "\en";
.Ve
.PP
You could add to the list this way:
.PP
.Vb 5
\&    my ($head, $tail);
\&    $tail = append($head, 1);       # grow a new head
\&    for $value ( 2 .. 10 ) {
\&        $tail = append($tail, $value);
\&    }
.Ve
.PP
.Vb 11
\&    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;
\&    }
.Ve
.PP
But again, Perl's built-in are virtually always good enough.
.Sh "How do I handle circular lists?"
.IX Subsection "How do I handle circular lists?"
Circular lists could be handled in the traditional fashion with linked
lists, or you could just do something like this with an array:
.PP
.Vb 2
\&    unshift(@array, pop(@array));  # the last shall be first
\&    push(@array, shift(@array));   # and vice versa
.Ve
.Sh "How do I shuffle an array randomly?"
.IX Subsection "How do I shuffle an array randomly?"
If you either have Perl 5.8.0 or later installed, or if you have
Scalar-List-Utils 1.03 or later installed, you can say:
.PP
.Vb 1
\&    use List::Util 'shuffle';
.Ve
.PP
.Vb 1
\&        @shuffled = shuffle(@list);
.Ve
.PP
If not, you can use a Fisher-Yates shuffle.
.PP
.Vb 8
\&    sub fisher_yates_shuffle {
\&        my $deck = shift;  # $deck is a reference to an array
\&        my $i = @$deck;
\&        while (--$i) {
\&            my $j = int rand ($i+1);
\&            @$deck[$i,$j] = @$deck[$j,$i];
\&        }
\&    }
.Ve
.PP
.Vb 5
\&    # shuffle my mpeg collection
\&    #
\&    my @mpeg = <audio/*/*.mp3>;
\&    fisher_yates_shuffle( \e@mpeg );    # randomize @mpeg in place
\&    print @mpeg;
.Ve
.PP
Note that the above implementation shuffles an array in place,
unlike the \fIList::Util::shuffle()\fR which takes a list and returns
a new shuffled list.
.PP
You've probably seen shuffling algorithms that work using splice,
randomly picking another element to swap the current element with
.PP
.Vb 6
\&    srand;
\&    @new = ();
\&    @old = 1 .. 10;  # just a demo
\&    while (@old) {
\&        push(@new, splice(@old, rand @old, 1));
\&    }
.Ve
.PP
This is bad because splice is already O(N), and since you do it N times,
you just invented a quadratic algorithm; that is, O(N**2).  This does
not scale, although Perl is so efficient that you probably won't notice
this until you have rather largish arrays.
.Sh "How do I process/modify each element of an array?"
.IX Subsection "How do I process/modify each element of an array?"
Use \f(CW\*(C`for\*(C'\fR/\f(CW\*(C`foreach\*(C'\fR:
.PP
.Vb 4
\&    for (@lines) {
\&                s/foo/bar/;     # change that word
\&                tr/XZ/ZX/;      # swap those letters
\&    }
.Ve
.PP
Here's another; let's compute spherical volumes:
.PP
.Vb 4
\&    for (@volumes = @radii) {   # @volumes has changed parts
\&                $_ **= 3;
\&                $_ *= (4/3) * 3.14159;  # this will be constant folded
\&    }
.Ve
.PP
which can also be done with \fImap()\fR which is made to transform
one list into another:
.PP
.Vb 1
\&        @volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii;
.Ve
.PP
If you want to do the same thing to modify the values of the
hash, you can use the \f(CW\*(C`values\*(C'\fR function.  As of Perl 5.6
the values are not copied, so if you modify \f(CW$orbit\fR (in this
case), you modify the value.
.PP
.Vb 3
\&    for $orbit ( values %orbits ) {
\&                ($orbit **= 3) *= (4/3) * 3.14159;
\&    }
.Ve
.PP
Prior to perl 5.6 \f(CW\*(C`values\*(C'\fR returned copies of the values,
so older perl code often contains constructions such as
\&\f(CW@orbits{keys %orbits}\fR instead of \f(CW\*(C`values %orbits\*(C'\fR where
the hash is to be modified.
.Sh "How do I select a random element from an array?"
.IX Subsection "How do I select a random element from an array?"
Use the \fIrand()\fR function (see \*(L"rand\*(R" in perlfunc):
.PP
.Vb 2
\&    $index   = rand @array;
\&    $element = $array[$index];
.Ve
.PP
Or, simply:
    my \f(CW$element\fR = \f(CW$array\fR[ rand \f(CW@array\fR ];
.Sh "How do I permute N elements of a list?"
.IX Subsection "How do I permute N elements of a list?"
Use the List::Permutor module on \s-1CPAN\s0.  If the list is
actually an array, try the Algorithm::Permute module (also
on \s-1CPAN\s0).  It's written in \s-1XS\s0 code and is very efficient.
.PP
.Vb 6
\&        use Algorithm::Permute;
\&        my @array = 'a'..'d';
\&        my $p_iterator = Algorithm::Permute->new ( \e@array );
\&        while (my @perm = $p_iterator->next) {
\&           print "next permutation: (@perm)\en";
\&        }
.Ve
.PP
For even faster execution, you could do:
.PP
.Vb 5
\&   use Algorithm::Permute;
\&   my @array = 'a'..'d';
\&   Algorithm::Permute::permute {
\&      print "next permutation: (@array)\en";
\&   } @array;
.Ve
.PP
Here's a little program that generates all permutations of
all the words on each line of input. The algorithm embodied
in the \fIpermute()\fR function is discussed in Volume 4 (still
unpublished) of Knuth's \fIThe Art of Computer Programming\fR
and will work on any list:
.PP
.Vb 2
\&        #!/usr/bin/perl -n
\&        # Fischer-Kause ordered permutation generator
.Ve
.PP
.Vb 12
\&        sub permute (&@) {
\&                my $code = shift;
\&                my @idx = 0..$#_;
\&                while ( $code->(@_[@idx]) ) {
\&                        my $p = $#idx;
\&                        --$p while $idx[$p-1] > $idx[$p];
\&                        my $q = $p or return;
\&                        push @idx, reverse splice @idx, $p;
\&                        ++$q while $idx[$p-1] > $idx[$q];
\&                        @idx[$p-1,$q]=@idx[$q,$p-1];
\&                }
\&        }
.Ve
.PP
.Vb 1
\&        permute {print"@_\en"} split;
.Ve
.Sh "How do I sort an array by (anything)?"
.IX Subsection "How do I sort an array by (anything)?"
Supply a comparison function to \fIsort()\fR (described in \*(L"sort\*(R" in perlfunc):
.PP
.Vb 1
\&    @list = sort { $a <=> $b } @list;
.Ve
.PP
The default sort function is cmp, string comparison, which would
sort \f(CW\*(C`(1, 2, 10)\*(C'\fR into \f(CW\*(C`(1, 10, 2)\*(C'\fR.  \f(CW\*(C`<=>\*(C'\fR, used above, is
the numerical comparison operator.
.PP
If you have a complicated function needed to pull out the part you
want to sort on, then don't do it inside the sort function.  Pull it
out first, because the sort \s-1BLOCK\s0 can be called many times for the
same element.  Here's an example of how to pull out the first word
after the first number on each item, and then sort those words
case\-insensitively.
.PP
.Vb 6
\&    @idx = ();
\&    for (@data) {
\&        ($item) = /\ed+\es*(\eS+)/;
\&        push @idx, uc($item);
\&    }
\&    @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
.Ve
.PP
which could also be written this way, using a trick
that's come to be known as the Schwartzian Transform:
.PP
.Vb 3
\&    @sorted = map  { $_->[0] }
\&              sort { $a->[1] cmp $b->[1] }
\&              map  { [ $_, uc( (/\ed+\es*(\eS+)/)[0]) ] } @data;
.Ve
.PP
If you need to sort on several fields, the following paradigm is useful.
.PP
.Vb 4
\&    @sorted = sort { field1($a) <=> field1($b) ||
\&                     field2($a) cmp field2($b) ||
\&                     field3($a) cmp field3($b)
\&                   }     @data;
.Ve
.PP
This can be conveniently combined with precalculation of keys as given
above.
.PP
See the \fIsort\fR article in the \*(L"Far More Than You Ever Wanted
To Know\*(R" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz for
more about this approach.
.PP
See also the question below on sorting hashes.
.Sh "How do I manipulate arrays of bits?"
.IX Subsection "How do I manipulate arrays of bits?"
Use \fIpack()\fR and \fIunpack()\fR, or else \fIvec()\fR and the bitwise operations.
.PP
For example, this sets \f(CW$vec\fR to have bit N set if \f(CW$ints\fR[N] was set:
.PP
.Vb 2
\&    $vec = '';
\&    foreach(@ints) { vec($vec,$_,1) = 1 }
.Ve
.PP
Here's how, given a vector in \f(CW$vec\fR, you can
get those bits into your \f(CW@ints\fR array:
.PP
.Vb 28
\&    sub bitvec_to_list {
\&        my $vec = shift;
\&        my @ints;
\&        # Find null-byte density then select best algorithm
\&        if ($vec =~ tr/\e0// / length $vec > 0.95) {
\&            use integer;
\&            my $i;
\&            # This method is faster with mostly null-bytes
\&            while($vec =~ /[^\e0]/g ) {
\&                $i = -9 + 8 * pos $vec;
\&                push @ints, $i if vec($vec, ++$i, 1);
\&                push @ints, $i if vec($vec, ++$i, 1);
\&                push @ints, $i if vec($vec, ++$i, 1);
\&                push @ints, $i if vec($vec, ++$i, 1);
\&                push @ints, $i if vec($vec, ++$i, 1);
\&                push @ints, $i if vec($vec, ++$i, 1);
\&                push @ints, $i if vec($vec, ++$i, 1);
\&                push @ints, $i if vec($vec, ++$i, 1);
\&            }
\&        } else {
\&            # This method is a fast general algorithm
\&            use integer;
\&            my $bits = unpack "b*", $vec;
\&            push @ints, 0 if $bits =~ s/^(\ed)// && $1;
\&            push @ints, pos $bits while($bits =~ /1/g);
\&        }
\&        return \e@ints;
\&    }
.Ve
.PP
This method gets faster the more sparse the bit vector is.
(Courtesy of Tim Bunce and Winfried Koenig.)
.PP
You can make the while loop a lot shorter with this suggestion
from Benjamin Goldberg:
.PP
.Vb 3
\&        while($vec =~ /[^\e0]+/g ) {
\&           push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8;
\&        }
.Ve
.PP
Or use the \s-1CPAN\s0 module Bit::Vector:
.PP
.Vb 3
\&    $vector = Bit::Vector->new($num_of_bits);
\&    $vector->Index_List_Store(@ints);
\&    @ints = $vector->Index_List_Read();
.Ve
.PP
Bit::Vector provides efficient methods for bit vector, sets of small integers
and \*(L"big int\*(R" math.
.PP
Here's a more extensive illustration using \fIvec()\fR:
.PP
.Vb 7
\&    # vec demo
\&    $vector = "\exff\ex0f\exef\exfe";
\&    print "Ilya's string \e\exff\e\ex0f\e\exef\e\exfe represents the number ",
\&        unpack("N", $vector), "\en";
\&    $is_set = vec($vector, 23, 1);
\&    print "Its 23rd bit is ", $is_set ? "set" : "clear", ".\en";
\&    pvec($vector);
.Ve
.PP
.Vb 3
\&    set_vec(1,1,1);
\&    set_vec(3,1,1);
\&    set_vec(23,1,1);
.Ve
.PP
.Vb 6
\&    set_vec(3,1,3);
\&    set_vec(3,2,3);
\&    set_vec(3,4,3);
\&    set_vec(3,4,7);
\&    set_vec(3,8,3);
\&    set_vec(3,8,7);
.Ve
.PP
.Vb 2
\&    set_vec(0,32,17);
\&    set_vec(1,32,17);
.Ve
.PP
.Vb 7
\&    sub set_vec {
\&        my ($offset, $width, $value) = @_;
\&        my $vector = '';
\&        vec($vector, $offset, $width) = $value;
\&        print "offset=$offset width=$width value=$value\en";
\&        pvec($vector);
\&    }
.Ve
.PP
.Vb 5
\&    sub pvec {
\&        my $vector = shift;
\&        my $bits = unpack("b*", $vector);
\&        my $i = 0;
\&        my $BASE = 8;
.Ve
.PP
.Vb 4
\&        print "vector length in bytes: ", length($vector), "\en";
\&        @bytes = unpack("A8" x length($vector), $bits);
\&        print "bits are: @bytes\en\en";
\&    }
.Ve
.Sh "Why does \fIdefined()\fP return true on empty arrays and hashes?"
.IX Subsection "Why does defined() return true on empty arrays and hashes?"
The short story is that you should probably only use defined on scalars or
functions, not on aggregates (arrays and hashes).  See \*(L"defined\*(R" in perlfunc
in the 5.004 release or later of Perl for more detail.
.SH "Data: Hashes (Associative Arrays)"
.IX Header "Data: Hashes (Associative Arrays)"
.Sh "How do I process an entire hash?"
.IX Subsection "How do I process an entire hash?"
Use the \fIeach()\fR function (see \*(L"each\*(R" in perlfunc) if you don't care
whether it's sorted:
.PP
.Vb 3
\&    while ( ($key, $value) = each %hash) {
\&        print "$key = $value\en";
\&    }
.Ve
.PP
If you want it sorted, you'll have to use \fIforeach()\fR on the result of
sorting the keys as shown in an earlier question.
.Sh "What happens if I add or remove keys from a hash while iterating over it?"
.IX Subsection "What happens if I add or remove keys from a hash while iterating over it?"
(contributed by brian d foy)
.PP
The easy answer is \*(L"Don't do that!\*(R"
.PP
If you iterate through the hash with \fIeach()\fR, you can delete the key
most recently returned without worrying about it.  If you delete or add
other keys, the iterator may skip or double up on them since perl
may rearrange the hash table.  See the
entry for \f(CW\*(C`each()\*(C'\fR in perlfunc.
.Sh "How do I look up a hash element by value?"
.IX Subsection "How do I look up a hash element by value?"
Create a reverse hash:
.PP
.Vb 2
\&    %by_value = reverse %by_key;
\&    $key = $by_value{$value};
.Ve
.PP
That's not particularly efficient.  It would be more space-efficient
to use:
.PP
.Vb 3
\&    while (($key, $value) = each %by_key) {
\&        $by_value{$value} = $key;
\&    }
.Ve
.PP
If your hash could have repeated values, the methods above will only find
one of the associated keys.   This may or may not worry you.  If it does
worry you, you can always reverse the hash into a hash of arrays instead:
.PP
.Vb 3
\&     while (($key, $value) = each %by_key) {
\&         push @{$key_list_by_value{$value}}, $key;
\&     }
.Ve
.Sh "How can I know how many entries are in a hash?"
.IX Subsection "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 \fIkeys()\fR function in a scalar context:
.PP
.Vb 1
\&    $num_keys = keys %hash;
.Ve
.PP
The \fIkeys()\fR 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 \fIeach()\fR.
.Sh "How do I sort a hash (optionally by value instead of key)?"
.IX Subsection "How do I sort a hash (optionally by value instead of key)?"
(contributed by brian d foy)
.PP
To sort a hash, start with the keys. In this example, we give the list of
keys to the sort function which then compares them ASCIIbetically (which
might be affected by your locale settings). The output list has the keys
in ASCIIbetical order. Once we have the keys, we can go through them to
create a report which lists the keys in ASCIIbetical order.
.PP
.Vb 1
\&        my @keys = sort { $a cmp $b } keys %hash;
.Ve
.PP
.Vb 4
\&        foreach my $key ( @keys )
\&                {
\&                printf "%-20s %6d\en", $key, $hash{$value};
\&                }
.Ve
.PP
We could get more fancy in the \f(CW\*(C`sort()\*(C'\fR block though. Instead of
comparing the keys, we can compute a value with them and use that
value as the comparison.
.PP
For instance, to make our report order case\-insensitive, we use
the \f(CW\*(C`\eL\*(C'\fR sequence in a double-quoted string to make everything
lowercase. The \f(CW\*(C`sort()\*(C'\fR block then compares the lowercased
values to determine in which order to put the keys.
.PP
.Vb 1
\&        my @keys = sort { "\eL$a" cmp "\eL$b" } keys %hash;
.Ve
.PP
Note: if the computation is expensive or the hash has many elements,
you may want to look at the Schwartzian Transform to cache the
computation results.
.PP
If we want to sort by the hash value instead, we use the hash key
to look it up. We still get out a list of keys, but this time they
are ordered by their value.
.PP
.Vb 1
\&        my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;
.Ve
.PP
From there we can get more complex. If the hash values are the same,
we can provide a secondary sort on the hash key.
.PP
.Vb 5
\&        my @keys = sort {
\&                $hash{$a} <=> $hash{$b}
\&                        or
\&                "\eL$a" cmp "\eL$b"
\&                } keys %hash;
.Ve
.Sh "How can I always keep my hash sorted?"
.IX Subsection "How can I always keep my hash sorted?"
You can look into using the DB_File module and \fItie()\fR using the
\&\f(CW$DB_BTREE\fR hash bindings as documented in \*(L"In Memory Databases\*(R" in DB_File.
The Tie::IxHash module from \s-1CPAN\s0 might also be instructive.
.ie n .Sh "What's the difference between ""delete"" and ""undef"" with hashes?"
.el .Sh "What's the difference between ``delete'' and ``undef'' with hashes?"
.IX Subsection "What's the difference between delete and undef with hashes?"
Hashes contain pairs of scalars: the first is the key, the
second is the value.  The key will be coerced to a string,
although the value can be any kind of scalar: string,
number, or reference.  If a key \f(CW$key\fR is present in
\&\f(CW%hash\fR, \f(CW\*(C`exists($hash{$key})\*(C'\fR will return true.  The value
for a given key can be \f(CW\*(C`undef\*(C'\fR, in which case
\&\f(CW$hash{$key}\fR will be \f(CW\*(C`undef\*(C'\fR while \f(CW\*(C`exists $hash{$key}\*(C'\fR
will return true.  This corresponds to (\f(CW$key\fR, \f(CW\*(C`undef\*(C'\fR)
being in the hash.
.PP
Pictures help...  here's the \f(CW%hash\fR table:
.PP
.Vb 7
\&          keys  values
\&        +------+------+
\&        |  a   |  3   |
\&        |  x   |  7   |
\&        |  d   |  0   |
\&        |  e   |  2   |
\&        +------+------+
.Ve
.PP
And these conditions hold
.PP
.Vb 6
\&        $hash{'a'}                       is true
\&        $hash{'d'}                       is false
\&        defined $hash{'d'}               is true
\&        defined $hash{'a'}               is true
\&        exists $hash{'a'}                is true (Perl5 only)
\&        grep ($_ eq 'a', keys %hash)     is true
.Ve
.PP
If you now say
.PP
.Vb 1
\&        undef $hash{'a'}
.Ve
.PP
your table now reads:
.PP
.Vb 7
\&          keys  values
\&        +------+------+
\&        |  a   | undef|
\&        |  x   |  7   |
\&        |  d   |  0   |
\&        |  e   |  2   |
\&        +------+------+
.Ve
.PP
and these conditions now hold; changes in caps:
.PP
.Vb 6
\&        $hash{'a'}                       is FALSE
\&        $hash{'d'}                       is false
\&        defined $hash{'d'}               is true
\&        defined $hash{'a'}               is FALSE
\&        exists $hash{'a'}                is true (Perl5 only)
\&        grep ($_ eq 'a', keys %hash)     is true
.Ve
.PP
Notice the last two: you have an undef value, but a defined key!
.PP
Now, consider this:
.PP
.Vb 1
\&        delete $hash{'a'}
.Ve
.PP
your table now reads:
.PP
.Vb 6
\&          keys  values
\&        +------+------+
\&        |  x   |  7   |
\&        |  d   |  0   |
\&        |  e   |  2   |
\&        +------+------+
.Ve
.PP
and these conditions now hold; changes in caps:
.PP
.Vb 6
\&        $hash{'a'}                       is false
\&        $hash{'d'}                       is false
\&        defined $hash{'d'}               is true
\&        defined $hash{'a'}               is false
\&        exists $hash{'a'}                is FALSE (Perl5 only)
\&        grep ($_ eq 'a', keys %hash)     is FALSE
.Ve
.PP
See, the whole entry is gone!
.Sh "Why don't my tied hashes make the defined/exists distinction?"
.IX Subsection "Why don't my tied hashes make the defined/exists distinction?"
This depends on the tied hash's implementation of \s-1\fIEXISTS\s0()\fR.
For example, there isn't the concept of undef with hashes
that are tied to DBM* files. It also means that \fIexists()\fR and
\&\fIdefined()\fR do the same thing with a DBM* file, and what they
end up doing is not what they do with ordinary hashes.
.Sh "How do I reset an \fIeach()\fP operation part-way through?"
.IX Subsection "How do I reset an each() operation part-way through?"
Using \f(CW\*(C`keys %hash\*(C'\fR in scalar context returns the number of keys in
the hash \fIand\fR resets the iterator associated with the hash.  You may
need to do this if you use \f(CW\*(C`last\*(C'\fR to exit a loop early so that when you
re-enter it, the hash iterator has been reset.
.Sh "How can I get the unique keys from two hashes?"
.IX Subsection "How can I get the unique keys from two hashes?"
First you extract the keys from the hashes into lists, then solve
the \*(L"removing duplicates\*(R" problem described above.  For example:
.PP
.Vb 5
\&    %seen = ();
\&    for $element (keys(%foo), keys(%bar)) {
\&        $seen{$element}++;
\&    }
\&    @uniq = keys %seen;
.Ve
.PP
Or more succinctly:
.PP
.Vb 1
\&    @uniq = keys %{{%foo,%bar}};
.Ve
.PP
Or if you really want to save space:
.PP
.Vb 8
\&    %seen = ();
\&    while (defined ($key = each %foo)) {
\&        $seen{$key}++;
\&    }
\&    while (defined ($key = each %bar)) {
\&        $seen{$key}++;
\&    }
\&    @uniq = keys %seen;
.Ve
.Sh "How can I store a multidimensional array in a \s-1DBM\s0 file?"
.IX Subsection "How can I store a multidimensional array in a DBM file?"
Either stringify the structure yourself (no fun), or else
get the \s-1MLDBM\s0 (which uses Data::Dumper) module from \s-1CPAN\s0 and layer
it on top of either DB_File or GDBM_File.
.Sh "How can I make my hash remember the order I put elements into it?"
.IX Subsection "How can I make my hash remember the order I put elements into it?"
Use the Tie::IxHash from \s-1CPAN\s0.
.PP
.Vb 7
\&    use Tie::IxHash;
\&    tie my %myhash, 'Tie::IxHash';
\&    for (my $i=0; $i<20; $i++) {
\&        $myhash{$i} = 2*$i;
\&    }
\&    my @keys = keys %myhash;
\&    # @keys = (0,1,2,3,...)
.Ve
.Sh "Why does passing a subroutine an undefined element in a hash create it?"
.IX Subsection "Why does passing a subroutine an undefined element in a hash create it?"
If you say something like:
.PP
.Vb 1
\&    somefunc($hash{"nonesuch key here"});
.Ve
.PP
Then that element \*(L"autovivifies\*(R"; that is, it springs into existence
whether you store something there or not.  That's because functions
get scalars passed in by reference.  If \fIsomefunc()\fR modifies \f(CW$_[0]\fR,
it has to be ready to write it back into the caller's version.
.PP
This has been fixed as of Perl5.004.
.PP
Normally, merely accessing a key's value for a nonexistent key does
\&\fInot\fR cause that key to be forever there.  This is different than
awk's behavior.
.Sh "How can I make the Perl equivalent of a C structure/\*(C+ class/hash or array of hashes or arrays?"
.IX Subsection "How can I make the Perl equivalent of a C structure/ class/hash or array of hashes or arrays?"
Usually a hash ref, perhaps like this:
.PP
.Vb 8
\&    $record = {
\&        NAME   => "Jason",
\&        EMPNO  => 132,
\&        TITLE  => "deputy peon",
\&        AGE    => 23,
\&        SALARY => 37_000,
\&        PALS   => [ "Norbert", "Rhys", "Phineas"],
\&    };
.Ve
.PP
References are documented in perlref and the upcoming perlreftut.
Examples of complex data structures are given in perldsc and
perllol.  Examples of structures and object-oriented classes are
in perltoot.
.Sh "How can I use a reference as a hash key?"
.IX Subsection "How can I use a reference as a hash key?"
(contributed by brian d foy)
.PP
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, \f(CW\*(C`HASH(0xDEADBEEF)\*(C'\fR). 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).
.PP
The Tie::RefHash module, which is distributed with perl, might be what
you want. It handles that extra work.
.SH "Data: Misc"
.IX Header "Data: Misc"
.Sh "How do I handle binary data correctly?"
.IX Subsection "How do I handle binary data correctly?"
Perl is binary clean, so this shouldn't be a problem.  For example,
this works fine (assuming the files are found):
.PP
.Vb 3
\&    if (`cat /vmunix` =~ /gzip/) {
\&        print "Your kernel is GNU-zip enabled!\en";
\&    }
.Ve
.PP
On less elegant (read: Byzantine) systems, however, you have
to play tedious games with \*(L"text\*(R" versus \*(L"binary\*(R" files.  See
\&\*(L"binmode\*(R" in perlfunc or perlopentut.
.PP
If you're concerned about 8\-bit \s-1ASCII\s0 data, then see perllocale.
.PP
If you want to deal with multibyte characters, however, there are
some gotchas.  See the section on Regular Expressions.
.Sh "How do I determine whether a scalar is a number/whole/integer/float?"
.IX Subsection "How do I determine whether a scalar is a number/whole/integer/float?"
Assuming that you don't care about \s-1IEEE\s0 notations like \*(L"NaN\*(R" or
\&\*(L"Infinity\*(R", you probably just want to use a regular expression.
.PP
.Vb 8
\&   if (/\eD/)            { print "has nondigits\en" }
\&   if (/^\ed+$/)         { print "is a whole number\en" }
\&   if (/^-?\ed+$/)       { print "is an integer\en" }
\&   if (/^[+-]?\ed+$/)    { print "is a +/- integer\en" }
\&   if (/^-?\ed+\e.?\ed*$/) { print "is a real number\en" }
\&   if (/^-?(?:\ed+(?:\e.\ed*)?|\e.\ed+)$/) { print "is a decimal number\en" }
\&   if (/^([+-]?)(?=\ed|\e.\ed)\ed*(\e.\ed*)?([Ee]([+-]?\ed+))?$/)
\&                        { print "a C float\en" }
.Ve
.PP
There are also some commonly used modules for the task.
Scalar::Util (distributed with 5.8) provides access to perl's
internal function \f(CW\*(C`looks_like_number\*(C'\fR for determining
whether a variable looks like a number.  Data::Types
exports functions that validate data types using both the
above and other regular expressions. Thirdly, there is
\&\f(CW\*(C`Regexp::Common\*(C'\fR which has regular expressions to match
various types of numbers. Those three modules are available
from the \s-1CPAN\s0.
.PP
If you're on a \s-1POSIX\s0 system, Perl supports the \f(CW\*(C`POSIX::strtod\*(C'\fR
function.  Its semantics are somewhat cumbersome, so here's a \f(CW\*(C`getnum\*(C'\fR
wrapper function for more convenient access.  This function takes
a string and returns the number it found, or \f(CW\*(C`undef\*(C'\fR for input that
isn't a C float.  The \f(CW\*(C`is_numeric\*(C'\fR function is a front end to \f(CW\*(C`getnum\*(C'\fR
if you just want to say, \*(L"Is this a float?\*(R"
.PP
.Vb 13
\&    sub getnum {
\&        use POSIX qw(strtod);
\&        my $str = shift;
\&        $str =~ s/^\es+//;
\&        $str =~ s/\es+$//;
\&        $! = 0;
\&        my($num, $unparsed) = strtod($str);
\&        if (($str eq '') || ($unparsed != 0) || $!) {
\&            return undef;
\&        } else {
\&            return $num;
\&        }
\&    }
.Ve
.PP
.Vb 1
\&    sub is_numeric { defined getnum($_[0]) }
.Ve
.PP
Or you could check out the String::Scanf module on the \s-1CPAN\s0
instead. The \s-1POSIX\s0 module (part of the standard Perl distribution) provides
the \f(CW\*(C`strtod\*(C'\fR and \f(CW\*(C`strtol\*(C'\fR for converting strings to double and longs,
respectively.
.Sh "How do I keep persistent data across program calls?"
.IX Subsection "How do I keep persistent data across program calls?"
For some specific applications, you can use one of the \s-1DBM\s0 modules.
See AnyDBM_File.  More generically, you should consult the FreezeThaw
or Storable modules from \s-1CPAN\s0.  Starting from Perl 5.8 Storable is part
of the standard distribution.  Here's one example using Storable's \f(CW\*(C`store\*(C'\fR
and \f(CW\*(C`retrieve\*(C'\fR functions:
.PP
.Vb 2
\&    use Storable;
\&    store(\e%hash, "filename");
.Ve
.PP
.Vb 3
\&    # later on...
\&    $href = retrieve("filename");        # by ref
\&    %hash = %{ retrieve("filename") };   # direct to hash
.Ve
.Sh "How do I print out or copy a recursive data structure?"
.IX Subsection "How do I print out or copy a recursive data structure?"
The Data::Dumper module on \s-1CPAN\s0 (or the 5.005 release of Perl) is great
for printing out data structures.  The Storable module on \s-1CPAN\s0 (or the
5.8 release of Perl), provides a function called \f(CW\*(C`dclone\*(C'\fR that recursively
copies its argument.
.PP
.Vb 2
\&    use Storable qw(dclone);
\&    $r2 = dclone($r1);
.Ve
.PP
Where \f(CW$r1\fR can be a reference to any kind of data structure you'd like.
It will be deeply copied.  Because \f(CW\*(C`dclone\*(C'\fR takes and returns references,
you'd have to add extra punctuation if you had a hash of arrays that
you wanted to copy.
.PP
.Vb 1
\&    %newhash = %{ dclone(\e%oldhash) };
.Ve
.Sh "How do I define methods for every class/object?"
.IX Subsection "How do I define methods for every class/object?"
Use the \s-1UNIVERSAL\s0 class (see \s-1UNIVERSAL\s0).
.Sh "How do I verify a credit card checksum?"
.IX Subsection "How do I verify a credit card checksum?"
Get the Business::CreditCard module from \s-1CPAN\s0.
.Sh "How do I pack arrays of doubles or floats for \s-1XS\s0 code?"
.IX Subsection "How do I pack arrays of doubles or floats for XS code?"
The kgbpack.c code in the \s-1PGPLOT\s0 module on \s-1CPAN\s0 does just this.
If you're doing a lot of float or double processing, consider using
the \s-1PDL\s0 module from \s-1CPAN\s0 instead\*(--it makes number-crunching easy.
.SH "AUTHOR AND COPYRIGHT"
.IX Header "AUTHOR AND COPYRIGHT"
Copyright (c) 1997\-2006 Tom Christiansen, Nathan Torkington, and
other authors as noted. All rights reserved.
.PP
This documentation is free; you can redistribute it and/or modify it
under the same terms as Perl itself.
.PP
Irrespective of its distribution, all code examples in this file
are hereby placed into the public domain.  You are permitted and
encouraged to use this code in your own programs for fun
or for profit as you see fit.  A simple comment in the code giving
credit would be courteous but is not required.
