note
LanX
Hi Gabor<P><P>
<I>> Why did the first example generate the warnings?</I><P><P>
Wrong question. Since [doc://sort] is a built-in, it was able to silence the warnings!<P><P>
<I>> What is the recommended way to silence them?</I><P><P>
Use them twice?<P><P>
<I>> Why is this not mentioned in List::Util?</I><P><P>
Maybe because the author is frustrated about not beeing able to simulate a built-in?<P><P>
Seriously ...<P><P>
... it's not that easy to design functional constructs with special variables in code-blocks like sort does.<P><P>
I tried it in [id://1020045|hgrep] and then I was confronted with many scoping problems, what if the block is defined within another package or if $a and $b are declared as lexicals?<P><P>
Look into the code of [MOD://Hash::MostUtils] to have an idea about the complications to solve all of this.<P><P>
I bet that [MOD://List::Util] couldn't solve all of this.<P><P>
<H5> UPDATE<P></H5><P>
To prove my last guess:<P><P>
This prints 55, but after uncommenting the second line its only 0 ...oops!
<c>
use List::Util qw/reduce/;
# my ($a,$b)=(0,0);
print reduce { $b+=$a } 1..10;
</c><P><P>
<H5> UPDATE<P></H5><P>
and here the same problem for [MOD://List::MoreUtils]<P><P>
<c>
use warnings;
use strict;
# my ($a,$b)=(0,0);
use List::MoreUtils qw/pairwise/;
my @a = (1 .. 5);
my @b = (11 .. 15);
my @x = pairwise { $a + $b } @a, @b; # returns 12, 14, 16, 18, 20
use Data::Dump;
dd \@x;
</c><P><P>
<H5> UPDATE<P></H5><P>
At least [doc://sort] simply dies<P><P>
<c>
my ($a,$b)=(0,0);
print sort { $b cmp $a } 1..10;
</c><P><P>
<c>
Can't use "my $b" in sort comparison at ... line 2.
</c><P><P>
<H5> Update</H5>
...but
<c>
use warnings;
use strict;
our ($a,$b);
package Tst;
print sort { $b cmp $a } 1..10;
</c>
<c>
Use of uninitialized value $b in string comparison (cmp) at /home/lanx/B/PL/PM/ScopeListUtils.pl line 9.
Use of uninitialized value $a in string comparison (cmp) at /home/lanx/B/PL/PM/ScopeListUtils.pl line 9.
Use of uninitialized value $b in string comparison (cmp) at /home/lanx/B/PL/PM/ScopeListUtils.pl line 9.
Use of uninitialized value $a in string comparison (cmp) at /home/lanx/B/PL/PM/ScopeListUtils.pl line 9.
...
</c>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-708738">
<p>Cheers Rolf
</div></div>
1021888
1021888