Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

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


Comment on Re: Eliminating "used only once" warnings from List::Util::reduce
Select or Download Code
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/Util.pm) 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.


    Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1046958]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2014-09-22 02:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (177 votes), past polls