On 2/26/09 Thu  Feb 26, 2009  3:53 PM, "John W. Krahn" <jwkr...@shaw.ca>
scribbled:

> Rick wrote:
>> trying out getting lasrgest key(by value) but below is not working...
>> 
>> help please.
>> 
>> my %files=%{{"one" =>"1", "thiry" =>"30", "four" =>"4", "never" =>"997",
>> "forever" =>"100001", "five" =>"5"}};
>> my $max;
>> print join(" ",keys %files),"\n";
>> 
>> =pod
>> grep($max=($files{$_} > $max )? $_ : $max,keys %files);
>> =cut
>> for my $jot (keys %files) {
>>        print "$jot $files{$jot}\n";
>> }
>> 
>> for my $now (keys %files) {
>>       $max = $now if $now > $max;       }
>>   
>> print "<$max>\n";
> 
> $ perl -le'
> my %files = ( one => 1, thiry => 30, four => 4, never => 997, forever =>
> 100001, five => 5 );
> my @max;
> for my $key ( keys %files ) {
>      if ( $files{ $key } > $max[ 1 ] ) {
>          @max[ 0, 1 ] = ( $key, $files{ $key } );
>          }
>      }
> print $max[ 0 ];
> '
> forever

I get "Use of uninitialized value in numeric gt (>) at ..." for that, since
@max is undefined the first time through the loop. Here is a version using
each that doesn't produce that error. It uses the fact that each saves its
state from one call to the next, even if the calls are not on the same line:

#!/usr/bin/perl
use strict;
use warnings;

my %files = ( one => 1, thirty => 30, four => 4, never => 997,
    forever => 100001, five => 5 );
my @max = each(%files);
while( my @next = each(%files) ) {
    @max = @next if $next[1] > $max[1];
}
print "biggest: (@max)\n";

__OUTPUT__
biggest: (forever 100001)



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to