Scully4Ever has asked for the wisdom of the Perl Monks concerning the following question:
I'm new to programming and Perl so I'm sorry if this is something easy. I'm running into issues trying to get the maximum value from multiple lines in a file. Inside while loop I receive max each time, outside the while loop I only receive the last value. I know I could sort these easily with the sort command but my end goal is to use this code alongside a work specific command instead of a file. The numbers will change depending on the users input so I would like to store them in an array or hash, look for one value specifically or else grab the line with the maximum values.
list:
455 DOG
1074 BIRD
605 CAT
850 FISH
my $animals = "/home/usr/workspace/list"; my %animals_hash; sub main { my @newlines; unless(open(INPUT, $animals)) { die "\nCannot open $animals\n"; } while(my $line = <INPUT>) { chomp $line; if ($line =~ /DUCK/) { print "Send to Building XX"; exit; } else { my ($sums, $animal) = split /\s+/, $line; %animals_hash = ( $animal => $sums, ); } } my @keylist = keys %animals_hash; my $max_key = pop @keylist; foreach (@keylist) { $max_key = $_ if $animals_hash{$_} > $animals_hash{$max_ke +y}; } print $max_key. " :: " . $animals_hash{$max_key} . "\n"; print Dumper(%animals_hash); close INPUT; } main();
Current Output: FISH :: 850
$VAR1 = 'FISH';
$VAR2 = '850';
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Max Value
by toolic (Bishop) on Jul 10, 2015 at 16:50 UTC | |
by Scully4Ever (Novice) on Jul 10, 2015 at 17:37 UTC |