Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using READDIR to scan files in order

Status
Not open for further replies.

GezH

Programmer
Joined
Aug 7, 2002
Messages
68
Hello, I have a simple script which uses the READDIR command to scan through some files in a directory.

I thought the script was fine, as it always scanned the files in date order. But when we moved the script onto a different server (with different OS) these files are now being scanned in a seemingly random order.

Is there a way of enforcing this so that it is always in date order? A flag maybe?

Many thanks!
 
foreach $inputFile (readdir INDIR)
{
next if($inputFile=~/^\./); # ignore . files
next if(-d $inputFile); # Ignore directories

# do stuff with the file...

}
 
the code you posted does not order anything.

- Kevin, perl coder unexceptional!
 
As I said, I didn't think I needed to - as it worked correctly in my environment. I want to know how I DO order it!
 
See how this works. Assumes you are in the directory where the files reside:

Code:
opendir(INDIR,$yourdir) or die "$!":
my @files = readdir INDIR;
close INDIR;
@files = sort {(stat($a))[9] <=> (stat($b))[9]} @files;
foreach my $inputFile (@files)
{
        next if($inputFile=~/^\./); # ignore . files
        next if(-d $inputFile); # Ignore directories

        # do stuff with the file...

}




- Kevin, perl coder unexceptional!
 
That's brilliant - thanks Kevin.

Out of interest, could this be made to work from a different directory to where the files are stored?
 
one way:

Code:
my $yourdir = 'path/to/files';
opendir(INDIR,$yourdir) or die "$!":
my @files = readdir INDIR;
close INDIR;
@files = sort {(stat("$yourdir/$a"))[9] <=> (stat("$yourdir/$b"))[9]} @files;
foreach my $inputFile (@files)
{
        next if("$yourdir/$inputFile" =~/^\./); # ignore . files
        next if(-d "$yourdir/inputFile"); # Ignore directories

        # do stuff with the file...

}

btw, hardly brilliant, this is very basic sorting, using the stat() function to get the desired file attribute to do the sorting with. But I appreciate the compliment. [smile]

- Kevin, perl coder unexceptional!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top