4

I wrote some program for Perl 5.26.1, using strict and warnings. So after some tests without a message I thought it's OK.

But when I ran the program wth older Perl 5.18.2, I suddenly got a warning about $main::a being used only once. Indeed, there was a mis-spelling where $a should have been $an actually.

I know that $a and $b have special semantics when used in a "sort block", but I wonder why in Perl 5.26.1 use of $a seems to be OK even outside such a block (My use was in a print statement within a function and some "else branch" within a nested loop).

The manual page (perlvar) says:

Special package variables when using "sort()", see "sort" in perlfunc. Because of this specialness $a and $b don't need to be declared (using "use vars", or "our()") even when using the "strict 'vars'" pragma. Don't lexicalize them with "my $a" or "my $b" if you want to be able to use them in the "sort()" comparison block or function.

So is there a rationale behind not warning the user, or is it a bug?

1 Answer 1

10

From the perl-5.20.0 delta:

=head2 $a and $b warnings exemption

The special variables $a and $b, used in C<sort>, are now exempt from "used
once" warnings, even where C<sort> is not used.  This makes it easier for
CPAN modules to provide functions using $a and $b for similar purposes.
[perl #120462]

So it was an intentional change.

Sign up to request clarification or add additional context in comments.

5 Comments

e.g. List::Util's reduce
Could you add references or examples where using $a or $b is important "to provide functions using $a and $b for similar purposes"? I thought $a and $b are some ancient low-level optimizations buried in the Perl core.
The standard way that Perl's built-in sort function works is that it temporarily sets $a and $b to the two values to be compared before calling the compare function. So it makes sense not to warn for $a and $b . As ikegami has pointed out, other people have written functions such as List::Util's reduce(), which use a similar pattern - i.e. the reduce method repeatedly sets $a and $b before calling the supplied block..
So maybe the perlvar manual page should add a comment stating that normal user programs should avoid using variables $a and $b.
$a and $b are already mentioned in perlvar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.