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
    The reason you only have 1 pair in the hash, instead of 4 pairs, is that you keep initializing the hash inside the while loop:
    %animals_hash = ( $animal => $sums, );

    Change that to:

    $animals_hash{$animal} = $sums;

    Here is a complete working example:

    use warnings; use strict; my %animals_hash; while (my $line = <DATA>) { chomp $line; my ( $sums, $animal ) = split /\s+/, $line; $animals_hash{$animal} = $sums; } use Data::Dumper; $Data::Dumper::Sortkeys=1; print Dumper(\%animals_hash); __DATA__ 455 DOG 1074 BIRD 605 CAT 850 FISH

    Outputs:

    $VAR1 = { 'BIRD' => '1074', 'CAT' => '605', 'DOG' => '455', 'FISH' => '850' };

      That worked great. Thank you!