I wrote something similar to cull old versions of RPMs from the directory where I download patches. The other posters are right about the problems with version numbers. I solved it by storing the version in the hash, and comparing the version whenever a duplicate was found. The downside is that the resulting hash ONLY has the latest version number for each application. That might or might not be an issue for you. To make the version numbers work right, I split them on /\./, so they could be compared as numbers. If you're not doing this with RPMs, you can just change the way the initial hash is loaded.
my %rpms;
my %files;
foreach my $file (<*.rpm>) {
# RPM-SPECIFIC STUFF:
my @result = `rpm -qp --queryformat "%{NAME}/%{ARCH}/%{VERSION}.%{RE
+LEASE}\n" $file`;
my ($name, $arch, $version) = split /\//, $result[0];
# END RPM-SPECIFIC STUFF
$name .= ":" . $arch;
if ( exists $rpms{$name} ) {
#decide which one we like better:
my @a = split /\./, $version;
my @b = split /\./, $rpms{$name};
my $i=0;
my $max = $#a > $#b ? $#a : $#b;
while ($i <= $max) {
if ( $a[$i] eq $b[$i] ) {
$i++;
next;
}
if ( $a[$i] lt $b[$i] ) {
print "rm -f $file\n";
last;
} else {
my $rm = "rm -f $files{$name}";
print "$rm\n";
`$rm` if lc($ARGV[0]) eq 'rm';
# or whatever else you want to do with old files.
last;
}
$i++;
}
} else {
$rpms{$name} = $version;
$files{$name} = $file;
}
}
Hope it helps.
--
Spring: Forces, Coiled Again!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.