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

Help with sort by creation date 1

Status
Not open for further replies.

nfaber

Technical User
Oct 22, 2001
446
US
My code below do3s not seem to be working. I want to read some files from a directory into an array and sort them by creation date:

#!/usr/contrib/bin/perl


use strict;
use warnings;

my $dir = "/OV_backup";
my @backups;
use vars qw($b $a);

opendir (DIR,$dir) or die ("Error opening $dir: $1");
my @files = readdir (DIR);
foreach (@files) {
next unless (/^OV_BACKUP.*/);
push (@backups,$_);
}
my @sort=sort {(-C $a) <=> (-C $b)} @backups;
print &quot;@sort\n&quot;;

Here is what I am getting:

&quot;Use of uninitialized value in numeric comparison (<=>)&quot;

and the files are not printed out in creation order in my print statement.

Any help appriciated.
 
The problem is that the file names are getting pushed onto the array without the path, so -C isn't finding the file.

You can change:
[tt]push @backups, $_;[/tt]
to:
[tt]push @backups, &quot;$dir/$_&quot;;[/tt]
 
A note on $a and $b -- this is from perlvar:

Special package variables when using sort(), see sort in the perlfunc manpage. Because of this specialness $a and $b don't need to be declared (using local(), use vars, or our()) even when using the strict vars pragma. Don't lexicalize them with my $a or my $b if you want to be able to use them in the sort() comparison block or function.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top