elbow has asked for the wisdom of the Perl Monks concerning the following question:

In my quest to amend an email conversion script, I've come across the following code to pull out files from a directory:-
while ($file = <$dir\\*.txt>) { #do your stuff }
Whenever I have had to access files from a directory before I've used the approach:-
opendir ( DIR, $dir ) || die "Cannot open directory $dir: $!"; while ( defined( $file = readdir(DIR) ) ) { next if $file =~ /^\.\.?$/; if ( $file =~/txt$/ ) { #do your stuff } } closedir DIR;
Benchmarking shows only a small difference in performance, with opendir the slightly better of the two.

All I want to know is - is there any other difference between the two approaches that I should take into account?

Or am I fussing over nothing? :-}

elbow

Update - I take back the slight difference part - benchmarking shows a huge difference between the two pieces of code on a directory with a lot of *.txt files in!

Replies are listed 'Best First'.
Re: opendir or not?
by davido (Cardinal) on Feb 02, 2004 at 09:06 UTC
    There's nothing inherently wrong with the glob approach you're using with the <> operator. The POD does warn against variable interpolation within a <> operator for readability reasons (perlop section on the < > operator):

    If you're trying to do variable interpolation, it's definitely better to use the glob() function, because the older notation can cause people to become confused with the indirect filehandle notation.

    @files = glob("$dir/*.[ch]"); @files = glob($files[$i]);

    Seems like a pretty minor nit. It sounds like you're fine.


    Dave

Re: opendir or not?
by Hena (Friar) on Feb 02, 2004 at 09:49 UTC
    Unless i read that wrong, then its not quite as portable. Eg. might not work for win or platform X that doensn't use "/" as path separator. Also consider filename 'my_file/with funky sep'.
Re: opendir or not?
by halley (Prior) on Feb 02, 2004 at 15:21 UTC
    You mentioned twice that there's a benchmark discrepancy between the while loop and the readdir loop. While you're in a benchmarking mood, if you're so inclined, please show us the results of the three forms:
    while ($eachfile = <*.txt>) { ... }
    @files = <*.txt>; foreach (@files) { ... }
    opendir(DIR, ...); while (defined ($eachfile = readdir(DIR) )) { next if not /\.txt$/; ... }

    Of course, there's platform differences to consider, too. Some filesystems bog down worse than others with long directories.

    If you're bored, check that @files = <*.txt> is really just as fast as @files = glob("*.txt"), too.

    --
    [ e d @ h a l l e y . c c ]