in reply to Sub in a Sub & Recursion
So why doesn't it print anything the second time? It's because &bar will have its own @files array but &foo will get a new array each time. So &foo and &bar will only share @files the first time &foo is run.sub foo { my @files; sub bar { push @files, @_; }; bar(@_); return @files; } print join ' ', foo(123, 456); # prints '123 456'. print join ' ', foo('abc', 'def'); # prints nothing.
my @files; sub foo { bar(@_); } sub bar { push @files, @_; } foo(123, 456); print join ' ', @files; # '123 456' foo('abc', 'def'); print join ' ', @files; # '123 456 abc def'
sub foo { @files = (); bar(@_); shift; foo(@_) if @_; }
sub foo { my @files; my $bar = sub { push @files, @_; }; $bar->(@_); return @files; } print join ' ', foo(123, 456); # '123 456' print join ' ', foo('abc', 'def'); # 'abc def'
sub foo { my @files; my $bar = sub { push @files, @_; }; $bar->(@_); shift; return @files, @_ ? foo(@_) : (); } print join ' ', foo(123, 456); # '123 456 456' print join ' ', foo('abc', 'def'); # 'abc def def'
|
|---|