$dir = "test";
mkdir $dir or die "Unable to create dir : $!" if not ( -d "$dir");
chdir $dir;
foreach ( 'aaa' .. 'zzz' ) {
open F, "> $_";
my $data = chr(97 + int rand 10);
print F $data;
close F;
}
####
use Benchmark qw/cmpthese/;
$dir = "test";
opendir DIR, "< $dir";
cmpthese(1000, {
'grep' => sub {
opendir DIR, "$dir" or die "Unable to open dir : $!\n";
@list=grep(!/^(\.+?)$/,readdir(DIR));
closedir DIR;
},
'while' => sub {
opendir DIR, "$dir" or die "Unable to open dir : $!\n";
while (readdir(DIR)) {
push @list, $_ unless /^(\.+?)$/;
closedir DIR;
}
}
});
##
##
D:\Perl\bin>perl test2.pl
Rate grep while
grep 6.51/s -- -100%
while 2667/s 40833% --
D:\Perl\bin>