in reply to $a and strict

$a and $b are special because they are used by sort, so there is an exception for them.

You should never use those as variable names. Among other problems, if you declare them with my, you will be unable to write custom sort functions afterwards. Oops.

Replies are listed 'Best First'.
Re: Re (tilly) 1: $a and strict
by John M. Dlugosz (Monsignor) on Jul 18, 2001 at 19:12 UTC
    Only within the scope of the my, or anywhere after?

    What about having the sort function qualify the names, eg. $main::a, to avoid that issue?

      There is only an issue with sort if you are not using the fully qualified package name and you are within the scope of a my declaration. (Or an our declaration from a different package.)

      Of course your co-workers may still want a clearer variable name...

        Of course, one can skirt the issue in version 5.6+ using prototypes because then the arguments arrive in @_ as with ordinary subroutines (though it will be slower than the package variable method):

        #!/usr/bin/perl -w use strict; package Foo; sub numeric1 ($$) { my($a, $b) = @_; # could use any variable names $a <=> $b } # or just sub numeric2 ($$) {$_[0] <=> $_[1]} package main; my($a, $b) = (13, 42); my @array = (3, 2, 5, 3, 4, 1); my @sorted1 = sort Foo::numeric1 @array; print "@sorted1\n"; my @sorted2 = sort Foo::numeric2 @array; print "@sorted2\n";
        Gotcha. So "best practice" would be to qualify the names in a function meant to be (re)used as a sort, and wish Perl generated a warning if a sort was called from a different package. Could do that myself, if a "debug mode" was enabled (a custom "use warning" setting, perhaps). Jumping through hoops to make the function work with the caller's package defeats the point of having $a,$b in the first place. So, create a fully-reusable (member of a class, whatnot) compare function that takes 2 args in the normal way; if someone wants to use it in a sort they call it from their local sort block: sort {Foo::compare($a,$b)} @list;. If you don't write functions meant to be directly used as a sort, the problem doesn't crop up.