Previous Page
Next Page

8.10. Hash Values

Make appropriate use of lvalue values.

Another builtin that can sometimes be used in an lvalue manner is the values function for hashes, though only in Perl 5.005_04 and later. Specifically, in recent Perls the values function returns a list of the original values of the hash, not a list of copies (as it did in Perl 5.005_03 and earlier).

This list of lvalues cannot be used in direct assignments:

    values(%seen_files) = (  );    # Compile-time error

but it can be used indirectly: in a for loop. That is, if you need to transform every value of a hash in some generic fashion, you don't have to index repeatedly within a loop:

    for my $party (keys %candidate_for) {
        $candidate_for{$party} =~ s{($MATCH_ANY_NAME)}

You can just use the result of values as individual lvalues:

    for my $candidate (values %candidate_for) {
        $candidate =~ s{($MATCH_ANY_NAME)}

The performance of the values-based version is also better. The loop's iterator variable is directly aliased to each hash value, so there's no need for (expensive) hash loop-ups inside the loop.

Stick with the indexing approach, however, if your code also has to support pre-5.6 compilers.

    Previous Page
    Next Page