On Tue, 11 Sep 2007 14:29:37 -0700, Tom Phoenix wrote:
> It is true that $a and $b are special during sort. But when there's no
> sorting going on, can using them cause the programmer any grief?
>
> I can see good reasons to avoid single-letter variable names as a
> matter of policy. And these two have the additional shortcoming is
> that 'use strict "vars"' is less careful about ensuring that they're
> declared as lexical variables. But perl was designed so that those
> variables could be used outside of a sort context just like any
> others; if it behaves otherwise, that's a bug.
>
> Has anyone seen another reason to avoid $a and $b? They don't seem all
> that dangerous.
If you do
my $a = 6.023E23; # Avagadro's number
# Many lines of chemistry code elided
@elements = sort { $atomic_wt{$a} <=> $atomic_wt{$b} } @elements;
you get
Can't use "my $a" in sort comparison
which is going to annoy someone who then has to change all the
references to Avagadro's number. If they then change the first line to
our $a = 6.023E23;
thinking that saves them time changing the references, they're fine
(aside from if any subroutines had decided to do the same thing) until
they need to refer to it in a sort routine... oops.
$a and $b get special treatment *outside* of sort blocks only because it
makes the performance of sort blocks a tiny bit faster than if they were
only special *inside* sort blocks... and speed trumps everything when
sorting.
That's a little contrived, and not necessarily "all that dangerous," but I
think it's easier to just make a blanket rule "Don't use $a or $b outside
of sort blocks" than teach/remember the stuff that you might have to know
if you do.
--
Peter Scott
http://www.perlmedic.com/
http://www.perldebugged.com/
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/