Date: Fri, 13 Jul 2001 14:30:42 +0100
From: "Andrew"
Subject: Re: List files in a directory
Message-Id: <9imt6a$nas$1@kermit.esat.net>
"Logan Shaw" wrote in message
news:9ime18$km8$1@charity.cs.utexas.edu...
> In article <9imd8n$fav$1@kermit.esat.net>, Andrew wrote:
> >for (0..$#files)
> >{
> > printf "$files[$_]\n";
> >}
>
> That's not really very much in the Perl idiom. It's much more natural
> to just do this:
>
> foreach (@files)
> {
> print "$_\n";
> }
>
I'll doing things that way from now on - so much less typing involved.
One thing I love about this group is that even answering questions can be a
great way to learn :-)
Going back to the part of the answers relevant to the OP, are there any big
differences between
@my_array = glob "*.sql";
and
while()
{
push @files,$_;
}
From reading the documentation for glob, it seems like they both do the
exact same thing, and I then discovered that I could do this;
@files = ;
Which is neater & shorter than my while loop (slightly faster too, according
to my benchmark (below). One question - why is the output given in the
order shown, which is different than the order in the script. (I don't mean
to imply that execution time would be a big reason to pick one way over
another for something like this..
Andrew
---------------------------------------------------------------
#!/usr/bin/perl
# Run on my perl scripts directory, containing 138 *.pl files
use strict;
use Benchmark;
my @array;
timethese(2000, {
'One' => '@array = glob "*.pl";',
'Two' => '@array = ',
'Three' => 'while (){ push @array,$_;}',
});
Benchmark: timing 2000 iterations of One, Three, Two...
One: 75 wallclock secs (19.91 usr + 53.58 sys = 73.48 CPU) @ 27.22/s
(n=2000)
Three: 78 wallclock secs (25.86 usr + 52.29 sys = 78.14 CPU) @ 25.59/s
(n=2000)
Two: 74 wallclock secs (20.92 usr + 52.63 sys = 73.55 CPU) @ 27.19/s
(n=2000)