Skip to content

Instantly share code, notes, and snippets.

@pdl
Created September 3, 2012 16:55
Show Gist options
  • Save pdl/3610796 to your computer and use it in GitHub Desktop.
Save pdl/3610796 to your computer and use it in GitHub Desktop.
Nested Subroutines in Perl - some odd behaviour
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