in reply to Sub in a Sub & Recursion

To my surprise it worked fine.

I'm surprised too. You should have gotten a 'Variable "@files" will not stay shared' warning.

Minimalistic example:
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.
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.

Another (expected) solution and its problems:
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'

We need to reset @files somewhere. OK. Let's add @files = () at the beginning of &foo.
There! Now it works... or not. It can't handle recursion. Let's modify &foo some more to make it a recursing subroutine:
sub foo { @files = (); bar(@_); shift; foo(@_) if @_; }

Now the output will be '456' and 'def' instead of '123 456 456' and 'abc def def' respectively. So we can't do the @files = () assigment in &foo. We need a wrapper. But what if the wrapper mysteriously gets recursive? Evil indeed...

My solution:
Keep it simple, keep it clean, keep it working.

The non-recursive solution to the original problem. (Of course rewritten as well, I'm just interested in showing the technique.)
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'

Here the inner subroutine gets recompiled each time resulting in @files always being the same as the one &foo uses.

Making it resursive:
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'

Viola!

I hope no one got confused by my rewritings from the original problem.

Cheers.