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

Re: Inner subroutines?

by blakew (Monk)
on Feb 11, 2011 at 04:05 UTC ( [id://887563]=note: print w/replies, xml ) Need Help??


in reply to Inner subroutines?

I've found scoping named subroutines useful when I want to initialize a data structure outside the subroutine but only visible to that one (or really as many as I want).
... { my @data = qw( this isn't visible elsewhere ); sub func { # Do something with @data here ... } } ...

You could do just as well inside another subroutine instead of just a bare block (@data is private to both subroutines), then you're working with closures. Typically though the inner subroutine is spawned anonymously and returned from the outer sub. For a good example of that see List::MoreUtils's natatime.

Seeing as how others have pointed out the inner sub is not really purposefully scoped (you redeclare your variable with 'my'), I'm guessing at what you're asking about. Higher Order Perl is a good book and one that I've been meaning to finish which talks all about closures and other things you can do with higher order functions.

Replies are listed 'Best First'.
Re^2: Inner subroutines?
by 7stud (Deacon) on Feb 17, 2011 at 21:08 UTC

    You could do just as well inside another subroutine instead of just a bare block

    I'm not seeing that:

    use warnings; use strict; use warnings; use strict; sub outer { my $data = 10; sub test { print $data; } } outer(); test(); --output:-- Variable "$data" will not stay shared at t.pl line 8. 10

    Nor here:

    use warnings; use strict; sub outer { my $data = 10; sub test { print $data; } test(); } outer(); --output:-- Variable "$data" will not stay shared at t.pl line 8. 10
      You're right it was a bad suggestion, I'm not sure what's going on here, it seems the variable isn't initialized until a call to outer; subsequent calls to outer() don't retain the initial reference but inner() does?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-03-28 17:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found