Created
September 3, 2012 16:55
-
-
Save pdl/3610796 to your computer and use it in GitHub Desktop.
Nested Subroutines in Perl - some odd behaviour
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
my @LINES = qw(artichoke beetroot cabbage); | |
while (my $in = shift(@LINES)) { | |
my $results = []; | |
sub result { | |
push @$results, shift; | |
} | |
result(uc $in); | |
print "\n$in"; | |
print "\n\t$_" foreach @$results; | |
} | |
print "\n---"; | |
@LINES = qw(artichoke beetroot cabbage); | |
while (my $in = shift(@LINES)) { | |
my $results = []; | |
my $result = sub { | |
push @$results, shift; | |
}; | |
&{$result}(uc $in); | |
print "\n$in"; | |
print "\n\t$_" foreach @$results; | |
} | |
=pod | |
Prints the following: | |
artichoke | |
ARTICHOKE | |
beetroot | |
cabbage | |
--- | |
artichoke | |
ARTICHOKE | |
beetroot | |
BEETROOT | |
cabbage | |
CABBAGE | |
But why? | |
The second is the 'expected' behaviour, I have no idea why the behaviour in the first is desirable - it seems like there is something going on behind the scenes... Is the first C<$results> being kept but no longer accessible except through C<&result>? | |
=cut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment