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?