Scott Palmer wrote:
> I am attempting to sort by a field in a hash within a hash and I am
> having a hard time finding the right direction. I want the print out to
> sort from smallest to largest in size. Any help would be greatly
> appreciated.
>
> ------------------------------------------
> #!/usr/bin/perl
The second and third lines of your program should be:
use warnings;
use strict;
> # Set your size/time requirements
> $minsize = 50; # Expressed in Megabytes
> $maxtime = 90; # Expressed in days
>
> # Define modules we need
> use File::Find;
> use Time::Local;
>
> # Get defined inputs and convert them to something we can use
> $nosmaller = ($minsize * 1024);
> $nonewer = ($maxtime * 86400);
> $time = timelocal($seconds, $minutes, $hours, (localtime)[3,4,5]);
You haven't defined the variables $seconds, $minutes and $hours anywhere?
> $timecomp = ($time - $nonewer);
>
> %tmp = ();
> # setup temp hash
> $count = 0;
You are using a numerical index so you should probably use an Array of Hashes
instead of a Hash of Hashes.
> sub wanted {
> my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev,
> $size, $atime, $mtime, $ctime,) = stat($_);
> if ($atime < $timecomp) {
Instead of using the file's atime you could use the -A operator which is the
file's atime in days.
> if ($size > $nosmaller) {
> $count++;
> my $filename = $File::Find::name;
> my ($name) = getpwuid($uid);
No need for list context there.
> my $osize = ($size / 1024 / 1024);
> $tmp{$count}{owner} = $name;
> $tmp{$count}{size} = $osize;
> $tmp{$count}{file} = $filename;
> }
> }
> }
>
> File::Find::find({wanted => \&wanted}, @ARGV);
>
> # Print out hash table
> for $count ( keys %tmp ) {
> printf "%10s %12.2f MB $tmp{$count}{file} \n",
Ouch! Putting interpolated variables in a printf format string is risky and
should be avoided.
> $tmp{$count}{owner}, $tmp{$count}{size};
> }
> exit;
You probably want something like:
#!/usr/bin/perl
use warnings;
use strict;
# Set your size/time requirements
my $minsize = 50; # Expressed in Megabytes
my $maxtime = 90; # Expressed in days
# Define modules we need
use File::Find;
# Get defined inputs and convert them to something we can use
my $nosmaller = $minsize * 1024;
my @tmp;
sub wanted {
my $owner = getpwuid( ( stat )[ 4 ] );
return if $maxtime > -A _;
return if $nosmaller > -s _;
push @tmp, {
owner => $owner,
size => ( -s _ ) / 1024 / 1024,
file => $File::Find::name,
};
}
find( { wanted => \&wanted }, @ARGV );
# Print out hash table
for my $hash ( sort { $a->{ size } <=> $b->{ size } } @tmp ) {
printf "%10s %12.2f MB %s\n", @{ $hash }{ qw( owner size file ) };
}
exit 0;
__END__
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>