N
niall.macpherson
I have some code which reads a number of key / value pairs. It needs to
store the largest value encountered for each key in the data in a hash.
This example code does what I want but I am sure there must be a better
way of doing it as the if(defined ...) part looks messy to me. If I
remove the if defined(...) check , then of course the line.
if($value > $biggest{$key})
gives a warning
Use of uninitialized value in numeric gt (>) at
C:\develop\NiallPerlScripts\clpm
14.pl line 14, <DATA> line 1.
the first time a new key is encountered.
Can anyone suggest a better way of writing this ?
--------------------------------- Start code
------------------------------------------------------------
use strict;
use warnings;
use Data:
umper;
my %biggest;
while(<DATA>)
{
chomp;
my($key, $value) = split(/,/);
if(defined ($biggest{$key}))
{
if($value > $biggest{$key})
{
$biggest{$key} = $value;
}
}
else
{
$biggest{$key} = $value;
}
}
print Dumper \%biggest;
__DATA__
1,123
2,234
3,356
2,444
3,666
--------------------------------- End code
store the largest value encountered for each key in the data in a hash.
This example code does what I want but I am sure there must be a better
way of doing it as the if(defined ...) part looks messy to me. If I
remove the if defined(...) check , then of course the line.
if($value > $biggest{$key})
gives a warning
Use of uninitialized value in numeric gt (>) at
C:\develop\NiallPerlScripts\clpm
14.pl line 14, <DATA> line 1.
the first time a new key is encountered.
Can anyone suggest a better way of writing this ?
--------------------------------- Start code
------------------------------------------------------------
use strict;
use warnings;
use Data:
my %biggest;
while(<DATA>)
{
chomp;
my($key, $value) = split(/,/);
if(defined ($biggest{$key}))
{
if($value > $biggest{$key})
{
$biggest{$key} = $value;
}
}
else
{
$biggest{$key} = $value;
}
}
print Dumper \%biggest;
__DATA__
1,123
2,234
3,356
2,444
3,666
--------------------------------- End code