in reply to Its not supposed to!

It would except that @dirs is not local to any one instance of the GetDirs function. That is, the push command modifies the same @dirs that is being redefined.

For example, suppose /tmp contains:

/tmp/chromatic /tmp/isotope
On the first recursion, the parent directory is /tmp. The glob picks up chromatic/ and isotope/. @dirs is empty.

It recurses to chromatic/ and picks up a bunch of files there, but none are directories. It returns the empty @dirs. That brings us to the push, and we put chromatic/ into @dirs.

Next, it moves on to isotope/. @dirs contains only chromatic/. As there are only files in isotope/, it doesn't push anything. It returns @dirs (still containing chromatic/) and then reaches the point where it pushes isotope/ onto the array.

As there is nothing left to check from the glob, it returns @dirs, now containing chromatic/ and isotope/. Recursion and global variables are subtle this way.

It's the push statement that makes it right. If you only did an assignment to @dirs, it would be wrong.

Replies are listed 'Best First'.
RE: Re: Its not supposed to!
by BBQ (Curate) on Apr 18, 2000 at 04:57 UTC
    I *think* I get it...

    What you're saying is that I could as well do this
    foreach $leaf (glob("$startdir/*")) { if (-d $leaf) { $trash = GetDirs($leaf); push(@dirs,$leaf); } }
    because it would still recurse, and it really doesn't matter what I'm assigning the return of the recursion (like $trash) because I'm pushing every $leaf to @dirs right after anyway? What really matters is the return of the 1st call and not the $trash.

    Or was that totally off track?

    BTW: You're explanations are always fun to read... Thanx!
      You don't even need the assignment to $trash in there, as the function might as well be declared void (in C or C++, if you're familiar). What you're concerned about is the side-effect of the subroutine.

      I tried to come up with a better way to do that, without the global variable, but I think you've hit on the clearest method with that recursion.

      (BTW, there is an account for isotope on this machine, though not under that nickname. Thanks for the kind words.)