[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] That was productive...



Nathan Torkington <gnat@frii.com> writes:
> ObPerl: one of the mistakes I find myself making often (but which, thank
> goodness, use strict catches) is saying
> 
>   @names = ....;
> 
> and then
> 
>   $name[1]
> 
> i.e., plural when I talk about the array as a whole, but singular when I
> talk about an element.

I noticed something similar a while back.  I actually wrote up a brief piece
about it with the vague intention of maybe expanding on it at some point,
but just now it doesn't look like I'll manage that.  So here it is, just in
case anyone's interested.

Variable name punning
=====================

It seems that it would be sensible to name arrays as plural nouns.  Thus in
Perl, you'd have things like @entries (`array of entries') and @filenames
(`array of file names').  But this is butt-ugly, if you'll pardon my French.
The obvious problem is that when you index such an array name, you get the
nonsensical result $entries[0] when $entry[0] would make more sense.  So I
habitually use singular names for arrays, just as for individual (scalar)
values.

This naming scheme also looks nice in certain Perl looping constructs;
though I'm not sure if I particularly recommend this usage.  This second bit
is in fact what causes me to term this practice `variable name punning'.
The idea is that you can say

    foreach (@entry) { ... }

and read this as the English `for each entry'.  This looks really elegant,
but note that we're really punning on the naming scheme -- we've selected an
array name which fortuitously appears to be a loop control variable name.
Of course, we're really using the default variable $_ as the loop control
variable.  The difference can readily be spotted in code like

    foreach my $entry (@entry) { ... }

Here we distinguish between our loop control variable ($entry) and the list
we're looping over (@entry).  This gets pronounced `for each entry in the
entry array.  Such a pronunciation is more long-winded; I cannot decide
whether that makes it more or less clear than the punning version.

-- 
Aaron Crane   <aaron.crane@pobox.com>   <URL:http://pobox.com/~aaronc/>

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe