in reply to Re: Split a string into items of constant length
in thread Split a string into items of constant length

Just a minor nitpick that is always worth to repeat, IMHO: $a should not be used as a general purpose variable -- see sort.

Update: (especially for those who didn't like this post) sauoq explained in greater detail the potential issues with using $a and $b as general purpose variables. He also pointed out that, as is well known, in most cases it won't do much harm. However it was apparent that the person I was answering to was not aware of them and the OP appeared to be a newbie. So, in this context, I'm still convinced it was an important circumstance to bring to their knowledge. Sad to notice more than one's mileage does vary...

Replies are listed 'Best First'.
Re^3: Split a string into items of constant length
by sauoq (Abbot) on Oct 04, 2005 at 11:25 UTC
    $a should not be used as a general purpose variable

    It's probably better to explain that rather than refer to a manpage that won't. At least, not very well. Yes, sort uses package variable $a and $b. It also localizes them.

    $ perl -le '$a="foo"; my @n = (3,2,1); print for sort {$a<=>$b} @n; pr +int $a' 1 2 3 foo
    It only becomes an issue if you declare them as lexical variables.
    $ perl -le 'my $a; my @n = (3,2,1); print for sort {$a<=>$b} @n' Can't use "my $a" in sort comparison at -e line 1.
    And the better fix is probably not to avoid $a and $b but to be explicit in your sort blocks and subs by using $::a and $::b (or $Foo::a and $Foo::b if you are in package Foo) explicitly.
    $ perl -le 'my $a; my @n = (3,2,1); print for sort {$::a<=>$::b} @n;' 1 2 3
    That isn't to say avoiding $a and $b is a bad thing... they are generally lousy variable names anyway. But I often use them in one-liners. So long as you know when and, more importantly, why it can be an issue, there's no harm in it.

    -sauoq
    "My two cents aren't worth a dime.";
    
      That isn't to say avoiding $a and $b is a bad thing... they are generally lousy variable names anyway. But I often use them in one-liners.
      Me too. Also in golf/obfu when I want to keep the code strict safe (even if there would be other built in vars available and provided that it's easy to do so), like in this one.