R. Joseph Newton wrote:
>
> Rob Dixon wrote:
>
> > Jeff Westman wrotenews:[EMAIL PROTECTED]
> > >
> > > I've never liked "recursion" but of course there are times where it is
> > > needed.
> > >
> > > I have a simple task that I am trying to do.  Basically, I just want to list
> > > out my directories on disk, and then chdir to each one, print it out, and so
> > > on.  Pretty basic, but I have a total mental block using recursion.
> > >
> > > Any quick help or tips would be appreciated.
> >
> > File::Find would do it for you, but the recursion is very
> > simple really:
>
> HI Rob,
>
> This is great, but could use just a bit of textual explanation:
>
> >
> >
> >   use strict;
> >   use warnings;
> >
> >   printdir('/usr');
> >
> >   sub printdir {
> >
> >     my $dir = shift;
> >
> >     opendir DIR, $dir or die $!;
> >     my @dirs = grep /[^.]/, readdir DIR;
> >     closedir DIR;
> >
> >     foreach (map "$dir/$_", @dirs) {
> >       if (-d) {                           #  recursive case
> >         printdir($_);
> >       }
> >       elsif (-f _) {
> >         print $_, "\n";                 #stopping case
> >       }
> >     }
> >   }
> >
> > HTH,
> >
> > Rob
>
> Doesn't take much.  Recursion is, as you say, fairly simple in its essence.  I
> just thought that it would be good to explicitly point out the need for a stopping
> case to prevent infinite recursion.

I'm not sure the idea of a 'stopping case' is relevant here. That is more
useful when recursion is used to evaluate one function in terms of another
simpler one, as in the classic

  sub factorial {
    my $x = shift;
    $x > 1 ? $x * factorial($x - 1) : 1;
  }

when there must be a case where the function is no longer reduceable
and has a value defined non-recursively. Scanning directory
recursively works because the data structure is recursive, and cannot
fail to terminate as long as there are no loops in the data (which is
true here since the code ignores symbolic links).

Cheers,

Rob



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to