oha has asked for the wisdom of the Perl Monks concerning the following question:

hi, after reading Re^2: Array question i got surprised and (other then RTFM as suggested by GrandFather) i tried to do some test.

  • in use strict if you declare my $a before the sort you'll get a compile time error; so there are no risk of using $a or $b. i tought it could be frustrating if, later, you need to use a sort and you have to change $a and $b, but you can: sort {$::a cmp $::b} @array and you can avoid the frustration.
  • without use strict instead, all went fine. so i suspected a trap here! the value of $a and $b could had be changed in the sort!
    but seems to me they are local and the old value is kept.
  • Am i wrong or the "magicness" of $a and $b is only matter of compilation semantic?
    does that mean we have not to be worried about using $a and $b, but only reckon the compile time error while use strict?

    Oha

    disclaimer: i want not encourage the use $a and $b, but i would like to understand more the inners of perl and what happen if they are used.

    Replies are listed 'Best First'.
    Re: magic $a, $b and sort
    by polettix (Vicar) on Sep 05, 2007 at 15:08 UTC
      I tried to reproduce but without luck, it complains independently of strict:
      #!/usr/bin/perl #use strict; #use warnings; #use diagnostics; my $a; my @array = sort { $a <=> $b } 19, 28, 1 .. 3; print "@array\n"; __END__ Can't use "my $a" in sort comparison at oha2.pl line 7
      Which version of perl are you using? I tested it with 5.8.4 and 5.8.8, both on Linux.

      Flavio
      perl -ple'$_=reverse' <<<ti.xittelop@oivalf

      Don't fool yourself.
        5.8.4 linux, but you are right. probably i used $::a while my $a, sorry :(

        Oha

        PS: i also found that the $a and $b are considered magic in perlvar too