i need some perl code for the following problem. thanks in advance for your efforts.
my input is in a file in this format: 'name' 'version number'
tech-sgla-zustand-ts.ini 1.1
tech-sgla-zustand-ts-feld.ini 1.1
tech-sgla-stamm-cds-feld.ini 1.1
tech-sgla-zustand-ts-feld.ini 1.2
tech-sgla-zustand-ts-feld.ini 1.4
tech-sgla-zustand-ts-feld.ini 1.3
i need it in the format (without blank lines in between): the 'name' should be unique with maximum 开发者_运维百科'version number'
tech-sgla-zustand-ts.ini 1.1
tech-sgla-zustand-ts-feld.ini 1.4
tech-sgla-stamm-cds-feld.ini 1.1
You could use :
my %iniFiles = ();
while (<>) {
my ($ini, $vers) = split / +/, $_;
if (exists $iniFiles{$ini}) {
$iniFiles{$ini} = $vers if ($iniFiles{$ini} < $vers);
} else { $iniFiles{$ini} = $vers }
}
while (my ($k,$v) = each %iniFiles) { print "$k $v\n" }
Or if the input order is important :
my @inis = ();
my %iniFiles = ();
while (<>) {
my ($ini, $vers) = split / +/, $_;
if (exists $iniFiles{$ini}) {
$iniFiles{$ini} = $vers if ($iniFiles{$ini} < $vers);
} else { push @inis, $ini; $iniFiles{$ini} = $vers }
}
foreach (@inis) { print "$_ $iniFiles{$_}\n" }
If the output order doesn't matter you can use this one-liner:
perl -ane '$h{$F[0]} = $F[1] if $F[1] > $h{$F[0]};
END { print "$_ $h{$_}\n" for keys %h }' file
Otherwise this script should do it:
my (%h, @a);
while (<>) {
my ($name, $ver) = split;
push @a, $name unless exists $h{$name};
$h{$name} = $ver if $ver > $h{$name} ;
}
print "$_ $h{$_}\n" for @a;
open(TOUT, "temp.txt");
while($line = <TOUT>){
my ($ini, $vers) = split / +/, $line;
print "ini $ini vers $vers";
if (exists $iniFiles{$ini}) {
$iniFiles{$ini} = $vers if ($iniFiles{$ini} < $vers);
}
else {
$iniFiles{$ini} = $vers;
}
}
print "\n";
while (my ($k,$v) = each %iniFiles) {
print "$k $v";
$ssldata = $k . " " . $v;
}
Thanks OMG_peanuts for ur responce, but i needed to modify it a little bit to get it working according to my requirement.
Thanks to eugene y as well for ur responce.
精彩评论