Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Perl warn about using `$a` outside of sort block anymore?

Tags:

variables

perl

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?

like image 227
U. Windl Avatar asked Oct 15 '25 16:10

U. Windl


1 Answers

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.

like image 112
Dave Mitchell Avatar answered Oct 18 '25 20:10

Dave Mitchell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!