develooper Front page | perl.perl5.porters | Postings from December 2015

no '"my $b" used in sort comparison' warning when $b is dereferenced?

Thread Next
From:
Christian Millour
Date:
December 17, 2015 01:29
Subject:
no '"my $b" used in sort comparison' warning when $b is dereferenced?
Message ID:
56720FEB.3070000@abtela.com
Hi,

I don't know whether this qualifies as a bug but please consider the 
following :

$ perl -V | head -1
Summary of my perl5 (revision 5 version 22 subversion 0) configuration:
$ perl -wE '
   my $b = 1;
   say for sort { $a <=> $b } reverse 0 .. 3
   '
"my $b" used in sort comparison at -e line 1.
1
0
2
3
$

the result is bogus but at least there is a warning. Compare with

$ perl -wE '
   my $b = [1,1];
   say for map $_->[0] =>
           sort { $a->[1] <=> $b->[1] }
           map [$_,$_] =>
           reverse 0 .. 3
   '
1
0
2
3
$

bogus result again but no warning this time... It looks like no warning 
is produced when $a and $b are dereferenced as above in the sort block.

This looks like a regression from pre-5.018 behavior, which would error 
out even without -w :

$ perl -V | head -1
Summary of my perl5 (revision 5 version 10 subversion 1) configuration:
$ perl -E '
   my $b = [1,1];
   say for map $_->[0] =>
           sort { $a->[1] <=> $b->[1] }
           map [$_,$_] =>
           reverse 0 .. 3
   '
Can't use "my $b" in sort comparison at -e line 1.
$

I understand the handling of $a and $b underwent a major overhaul in 
5.018 with many edge cases sorted out. However, could there be a bit 
more safety for users of Schwartzian transforms as in the example above 
(vastly simplified as compared to the original buggy code that prompted 
this investigation...) ?

Or, at least, some cautionary note in perldoc -f sort ?

Also, I wonder if a possible workaround would be to add a 'our ($a,$b)' 
declaration in the sort block. This seems to work on this example :

$ perl -E '
   my $b = [1,1];
   say for map $_->[0] =>
           sort { our ($a, $b); $a->[1] <=> $b->[1] }
           map [$_,$_] =>
           reverse 0 .. 3
   '
0
1
2
3
$

In your opinion, how safe/costly is this workaround in practice ? Is it 
worth documenting ?

Thanks in advance, and best regards,

--Christian


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About