Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: foreach-loop-local var in sub

by Athanasius (Chancellor)
on Jan 21, 2013 at 16:33 UTC ( #1014491=note: print w/replies, xml ) Need Help??

in reply to foreach-loop-local var in sub

Hello warshall, and welcome to the Monastery!

Just to reinforce the explanations given by choroba and tobyink, here is what the Camel Book (4th Edition, page 358) says about Nested subroutines:

If you are accustomed (from other programming languages) to using subroutines nested within other subroutines, each with their own private variables, you’ll have to work at it a bit in Perl. Named subroutines do not nest properly, although anonymous ones do.9

9 To be more precise, globally named subroutines don’t nest. Unfortunately, that’s the only kind of named subroutine declaration we have. We haven’t yet implemented lexically scoped, named subroutines (known as my subs), but when we do, they should nest correctly.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: foreach-loop-local var in sub
by tobyink (Abbot) on Jan 21, 2013 at 16:57 UTC

    FYI, Perl 5.18 will have experimental implementations of my sub, state sub and our sub. our sub is effectively the same as the existing sub keyword but can also be used to hide my sub subs, a la:

    use 5.010; our $foo = 42; my $foo = 99; say $foo; # says 99 our $foo; # "hides" my $foo say $foo; # says 42
    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

      I'm looking forward to my subs!

        > I'm looking forward to my subs!

        no need to wait it's just another syntax for my $sub =sub {}, just w/o the need to do dereferencing and occupying a scalar variable.

        from Re: foreach-loop-local var in sub:

        use strict; use warnings; foreach (0, 1) { my $i = $_; my $print = sub { print $i; }; $print->(); # 0,1 }

        Cheers Rolf

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (12)
As of 2018-04-20 09:46 GMT
Find Nodes?
    Voting Booth?