Section 3.4. Arrays and Hashes


3.4. Arrays and Hashes

Name arrays in the plural and hashes in the singular.

A hash is a mapping from distinct keys to individual values, and is most commonly used as a random-access look-up table. On the other hand, arrays are usually ordered sequences of multiple values, and are most commonly processed collectively or iteratively.

Because hash entries are typically accessed individually, it makes sense for the hash itself to be named in the singular. That convention causes the individual accesses to read more naturally in the code. Moreover, because hashes often store a property that's related to their key, it's often even more readable to name a hash with a singular noun followed by a preposition. For example:

      my %option;     my %title_of;     my %count_for;     my %is_available;     
# and later...
if ($option{'count_all'} && $title_of{$next_book} =~ m/$target/xms) { $count_for{$next_book}++; $is_available{$next_book} = 1; }

On the other hand, array values are more often processed collectively, in loops or in map or grep operations. So it makes sense to name them in the plural, after the group of items they store:

      my @events;     my @handlers;     my @unknowns;     
# and later...
for my $event (@events) { push @unknowns, grep { ! $_->handle($event) } @handlers; } print map { $_->err_msg } @unknowns;

If, however, an array is to be used as a random-access look-up table, name it in the singular, using the same conventions as for a hash:

      
# Initialize table of factorials
my @factorial = (1); for my $n (1..$MAX_FACT) { $factorial[$n] = $n * $factorial[$n-1]; }
# Check availability and look up in table
sub factorial { my ($n) = @_; croak "Can't compute factorial($n)" if $n < 0 || $n > $MAX_FACT; return $factorial[$n]; }



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net