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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help sorting and printing file in a directory 1

Status
Not open for further replies.

anthracite98

Programmer
Feb 19, 2001
3
US
Have a script the reads a directory of uploaded files and prints them out. I need to 1: sort them by date (newest printed first) and then 2: print the date next to the filename. Can anyone help me? thanks.
-mo

script below:
opendir(FILES,"$SAVE_DIRECTORY");
@allfiles = sort(grep(!/^\.\.?$/,readdir(FILES)));
closedir(FILES);
foreach$file(@allfiles) {
print "$file\n";
}

exit;
}
 
there are easier ways to do this with simple command line tools (ls), but the perl way isn't terribly difficult, so i'll give it to you.

the modification time of a file can be found with either of the following expressions:[tt]
$mtime = -M "filename";
or
$mtime = (stat("filename"))[9];[/tt]

the first returns the age in days (with decimal part), the second returns a unix time stamp. i'd suggest using the second.

then, to sort the filenames, use a swartzian transformation:[tt]

@sorted = map ( {$_->[1]}
sort( {$a->[0] <=> $b->[0]}
map ( {[(-M $_), $_]} @allfiles) ) );
[/tt]
&quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
a UNIX command line approach - just to illustrate another option.

#!/usr/local/bin/perl

@files = `ls -tl *`; # -t orders by last modify time. See 'man ls' for other options
foreach $file (@files)
{
my @stuff = split(/\s+/,$file);
printf &quot;%-25s%5s%4s%7s\n&quot;, ($stuff[8],$stuff[5],$stuff[6],$stuff[7]);
}


as always, with Perl, TMTOWTDI, :)


keep the rudder amid ship and beware the odd typo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top