Mathew Snyder wrote:
> John W. Krahn wrote:
>>>>
>>>>my @filenames;
>>>>my $processDir = "/usr/bin";
>>>>
>>>>opendir DH, $processDir or die "cannot open $processDir: $!";
>>>>foreach my $file (sort(readdir DH)){
>>>>        push @filenames, $file;
>>>>}
>>>Why not just:
>>>
>>>my @filenames = sort readdir DH;
> 
> Being new to Perl I want to learn the "long" and traditional way before
> I begin figuring out all the shortcuts.

Ahh!  You mean the non-Perl way.  ;-)


> Having been overwhelmed by all of the numerous options and possible
> methods of accomplishing this I took what I understood from everyone's
> suggestions and came up with this:
> 
> #!/usr/bin/perl
> 
> use warnings;
> use strict;
> 
> my $processDir = "/usr/bin";
> my @filenames;
> my $file_count = 0;
> 
> opendir DH, $processDir or die "cannot open $processDir: $!";
> foreach my $file (readdir DH){

More traditional would be to use a while loop:

while ( my $file = readdir DH ) {

This reads one entry at a time unlike the foreach loop which has to read all
the entries first.

>         next if ($file =~  /^\.]$|^\.\.$/);
>         push @filenames, $file;
> }
> closedir DH;
> 
> foreach my $filename (sort(@filenames)) {
>         $filename = "$processDir/$filename";
>         my $mod_time = (stat($filename))[9];
>         print "$filename: $mod_time\n";
>         $file_count += 1;
> }
> 
> print "\nThere are " . $file_count . " items in the filenames array.\n";

Since @filenames in scalar context equates to the number of entries in
@filenames you could just do this:

print "\nThere are " . @filenames . " items in the filenames array.\n";


> Dr. Ruud had mentioned that I was sorting too soon so I placed that in
> the second foreach loop.  I corrected the match expression and prepended
> the directory to each file prior to running stat on it but didn't save
> the new value to the array.  I was having a hard time understanding the
> -f option and the line with grep in it so I didn't bother with those
> this time around.  Perhaps I'll look into how to use them next time.

-f is a file test *operator*.  opendir/readdir will give you *all* entries in
a directory and you can use stat/lstat/file tests to distinguish between
"plain" files and other types of "files".

perldoc -f -X
perldoc -f stat



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to