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

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1014478]
Discipulus thanks back and passes around a weis bier in the berghastof hummelei celebrative glass

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2018-05-25 17:01 GMT
Find Nodes?
    Voting Booth?