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';


In reply to Max Value by Scully4Ever

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.