Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Eliminating "used only once" warnings from List::Util::reduce

by tobyink (Abbot)
on Jul 30, 2013 at 07:12 UTC ( #1046958=note: print w/replies, xml ) Need Help??

in reply to Eliminating "used only once" warnings from List::Util::reduce

If sort BLOCK LIST is encountered in a package, Perl switches off "used only once" warnings for the $a and $b package variables.

use warnings; use List::Util; my $reduced = List::Util::reduce { $a + $b } 1, 2, 3, 4; print "$reduced\n"; ()=sort{;}();

... that's why sort is magic.

List::Util could easily eliminate the warning; and it doesn't even need to use XS trickery to do so. It just needs to add something like this to its import method:

my $pkg = caller; eval qq[ package $pkg; our \$a; our \$b; ];

I believe the old pure Perl implementation of List::Util used to do something along these lines. It seems the shiny, new XS-only version does not. I'd count that as a regression.

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^2: Eliminating "used only once" warnings from List::Util::reduce
by davido (Archbishop) on Jul 30, 2013 at 18:54 UTC

    This is quite helpful, as it identifies why the XS code I referred to works for sort, and not for reduce, and provides a suggestion for how to solve it at the module level. I suspect that it could even still be fixed in the Perl portion of the List::Util module (List/ by overriding Exporter::import, and then from within the override, still calling the parent import. The one disadvantage I see in fixing this through import is that it doesn't deal with this:

    use warnings; use List::Util (); my $reduced = List::Util::reduce { $a + $b } 1,2,3,4;

    Import isn't called, and the warning will still occur (untested assertion). The simple retort to that is, well, if you do it that way, you've got to take responsibility for the warning. But I'm thinking that it still might be better just for perl to special-case $a and $b additionally, such that they're exempt from "only once" warnings altogether, just as they're exempt from strict vars.

    ...just thinking out loud. Thanks for your reply, it was helpful.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1046958]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2018-01-23 16:08 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (248 votes). Check out past polls.