Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: foreach-loop-local var in sub

by tobyink (Abbot)
on Jan 21, 2013 at 16:06 UTC ( #1014478=note: print w/ replies, xml ) Need Help??

in reply to foreach-loop-local var in sub

sub definitions within control structures don't really work how you want them to work. Your my_print function only gets defined once; not each time around the loop. If you want to redefine the sub each time around the loop, use an anonymous sub (a.k.a. closure; coderef) - which can be given a name by assigning it to a glob.

This works:

use strict; use warnings; no warnings 'redefine'; # stub to declare sub name, allowing it to be used # as a bareword later on sub my_print (); foreach my $i (0, 1) { *my_print = sub () { print "[$i]\n"; }; my_print; }
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Comment on Re: foreach-loop-local var in sub
Select or Download Code

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (6)
As of 2015-10-13 22:15 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (316 votes), past polls