Hi all,

The following perl program, for sorting files in a directory, without using
any OS specific command, ordered by modified timestamp is not working.

Please help.

*Perl Program*

#!perl.exe

use strict;
use warnings;

my $directory_name;
print "This program print the files in ascending order of timestamp.\n";
print "\n";
## print "Enter directory name : ";
##
## $directory_name = <STDIN>;
## chomp $directory_name;

$directory_name = "/tmp/test/";

die "ERROR : <<$directory_name>> is NOT a directory, $!\n" if ( ! -d
$directory_name );

my @files_in_directory;
opendir ( DIR1, $directory_name ) or die "Unable to open the directory
<<$directory_name>> : $!\n";
my $filename;
while ( defined ( $filename = readdir ( DIR1 ) ) )
{
        next if ( ( $filename eq "." ) or ( $filename eq ".." ) );

        push ( @files_in_directory, $filename );
}
closedir ( DIR1 );

print "Unsorted listing of files in <$directory_name> directory are as
follows :-\n";
my $i;
foreach $i ( @files_in_directory )
{
        print $i . "\n";
        # my ( $atime, $mtime, $ctime );
        #( undef, undef, undef, undef, undef, undef, undef, undef, $atime,
$mtime, $ctime, undef, undef ) = ( stat($i) );
        #print "atime=[$atime],mtime=[$mtime],ctime=[$ctime]\n";
        # print "atime=[" . (stat($i))[8] . "],mtime=[" . (stat($i))[9] .
"],ctime=[" . (stat($i))[10] . "]\n";
}
print "\n";

my @sorted_files_in_directory;
@sorted_files_in_directory = sort { (stat($a))[9] <=> (stat($b))[9] }
@files_in_directory;

print "Sorted listing of files in <$directory_name> directory are as follows
:-\n";
my $j;
foreach $j ( @files_in_directory )
{
        print $j . "\n";
}
print "\n";

*Directory Listing*

# ls -ltra /tmp/test/ | grep -v ^total | grep -v ^d
-rw-r--r--   1 root root 131699 Jan 12  2009 install.log.syslog
-rw-r--r--   1 root root  59020 Jan 12  2009 install.log
-rw-r--r--   1 root root   1267 Jan 12  2009 anaconda-ks.cfg
-rwxr-xr-x   1 root root   1574 May 21  2009 sys_bkp.pl
-rw-------   1 root root  17673 Jun  2  2009 mbox
-rw-------   1 root root   2630 Aug 17  2009 nohup.out1
-rw-------   1 root root   2630 Aug 17  2009 nohup.out2
-rw-r--r--   1 root root   1569 Dec  1 11:58 sort.pl

*Perl Program Output*

# perl /root/print_files_sort.pl
This program print the files in ascending order of timestamp.

Unsorted listing of files in </tmp/test/> directory are as follows :-
sys_bkp.pl
nohup.out2
nohup.out1
anaconda-ks.cfg
install.log
sort.pl
mbox
install.log.syslog

Sorted listing of files in </tmp/test/> directory are as follows :-
sys_bkp.pl
nohup.out2
nohup.out1
anaconda-ks.cfg
install.log
sort.pl
mbox
install.log.syslog

#



Thanks & Regards,
Amit Saxena

Reply via email to