On Jun 22, Aaron Lawson said:

>         I have a perl problem that seems like it should have a simple and 
>easy solution but that I can't figure out.  I am trying to determine which 
>of a set of scalars has the highest numeric value and then to get the NAME 
>of the scalar (not the value) to use this to tell a user what kind of file 
>they're dealing with.  Basically, the output of a long series of 
>calculations that analyzes newswire ends up with 5 numeric values (these 
>are scores for each domain): $financial, $sports, $foreigh_affairs, 
>$politics, $human_interest.  These five scalars are floating point numbers, 
>as I said, I'm just looking for some way of figuring out which has the 
>highest value and returning the name of the variable.

Two things:

  1. finding the NAME of a scalar is the wrong way to do things -- find
     the NAME of a key in a hash, instead
  2. generally, the easiest way to find the largest value in a list is to
     go through them one by one and stop when you find the largest ;)

But seriously, the easiest way to find the max in a list is:

  my $max;  # it is undef right now
  for (@list) { $max = $_ if !defined($max) or $_ > $max }

The hash idea would change your data to:

  %data = (
    financial => 6,
    sports => 3,
    foreign_affairs => 8,
    politics => 2,
    human_interest => 5,
  );

Then you would do:

  my $max;
  for (keys %data) {
    $max = $_ if !defined($max) or $data{$_} > $data{$max};
  }

Notice how I changed the if condition slightly -- you want to STORE the
name, but COMPARE via the hash-value.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
I am Marillion, the wielder of Ringril, known as Hesinaur, the Winter-Sun.
Are you a Monk?  http://www.perlmonks.com/     http://forums.perlguru.com/
Perl Programmer at RiskMetrics Group, Inc.     http://www.riskmetrics.com/
Acacia Fraternity, Rensselaer Chapter.         Brother #734
**      Manning Publications, Co, is publishing my Perl Regex book      **


Reply via email to