Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

In the code below

my $code_ref = sub { my $array_ref; my $nested_code_ref = sub { my @array = ("one","two","three"); $array_ref = \@array; }; $nested_code_ref->(); return $array_ref; }; print $code_ref->()->[0]; print $code_ref->()->[1];

Is it possible to call the anonymous block referenced by $nested_code_ref outside the anonymous block $code_ref.

Replies are listed 'Best First'.
Re: Nested references
by almut (Canon) on Apr 30, 2010 at 09:28 UTC

    Not directly (maybe using PadWalker or some such), unless you make it available to the outside, e.g. by returning it as an (optional) second value:

    #!/usr/bin/perl -l use strict; use warnings; my $code_ref = sub { my $array_ref; my $nested_code_ref = sub { my @array = ("one","two","three"); $array_ref = \@array; }; $nested_code_ref->(); return wantarray ? ($array_ref, $nested_code_ref) : $array_ref; }; print $code_ref->()->[0]; print $code_ref->()->[1]; print( ( $code_ref->() )[1]->()[2] ); __END__ $ ./837730.pl one two three

    We might be able to give a more useful answer, if you could explain your intention — from the question it's not really clear whether you want achieve or avoid that $nested_code_ref be accessible from the outside...

Re: Nested references
by moritz (Cardinal) on Apr 30, 2010 at 09:27 UTC
    Is it possible to call the anonymous block referenced by $nested_code_ref outside the anonymous block $code_ref.

    No. Unless you store it in a variable where it's accessible from the outside. (Or use something evil like PadWalker, but that's considered cheating).

    Perl 6 - links to (nearly) everything that is Perl 6.