in reply to recurse directories and sub-directories

just a wee snippet ..
sub handle_dir { my $d = shift; my $sd = shift || ''; my @all = (); opendir (DIR, $d) or die "Broken!"; while (defined(my $file = readdir(DIR))) { push @all, $file; } chdir ($d); foreach my $file (@all) { next if $file =~ /^\.$/; next if $file =~ /^\.\.$/; my $fp = $d . "\\" . $file; if ($file =~ /htm$/i) { &handle_html ($fp); } if (-d $file) { &handle_dir ($fp); } chdir($d); } chdir(".."); }
Just a qwik copy & paste .. scuse errors/ommissions the 'qif;

Replies are listed 'Best First'.
Re: Re: recurse directories and sub-directories
by tomhukins (Curate) on Oct 12, 2001 at 16:19 UTC

    You're much better off using File::Find than reinventing the wheel like this.

    Firstly, your code will only work on Windows, or any other OS where the directory separator is \. File::Find deals with this transparently. Also you're not checking for failure. What happens if the chdir ($d) fails, maybe because the directory specified in $d doesn't exist?

    The first two lines to match for the current or parent directory could be rewritten as next if $file =~ /^\.{1,2}$/;.

      The first two lines to match for the current or parent directory could be rewritten as next if $file =~ /^\.{1,2}$/;.

      But it would be better not to, because it is a potential time-bomb waiting to explode. Why do people keep dragging out this broken regexp, when a couple of conditionals will do the trick?

      next if $file eq '.' or $file eq '..';

      --
      g r i n d e r

        For the sake of defensive programming, and to be cross platform compatible, you could also use File::Spec::Functions to be safe.

        File::Spec::Functions has two routines that will return the characters used to represent the current and upper directory for your specific operating system. While it may be true that most OS's use "." and ".." to represent the current directory and upper directory, it may not necessarily be garaunteed. If it was, I doubt these functions would have been put into the module in the first place. =)

        Here's your example using File::Spec::Functions:

        use File::Spec::Functions qw(curdir updir); #.. next if $file eq curdir or $file eq updir;
Re: Re: recurse directories and sub-directories
by zuqif (Hermit) on Oct 12, 2001 at 17:12 UTC
    hokay - well ..
    Initiates rush in where abbots fear to tread I guess
    in future, for sake of any reputation I wanna maintain, will pause before submitting (:
    thems the breaks
    was a snippet from a program to generate an index of a cd of html content ..
    I mean, it works, but s'not exactly value-added-perl
    live n learn etc
    the 'qif;