I keep on getting initialization errors in this code on the use strict and can’t figure out why. I set the scope right for all the variables – and the codes runs. Just don’t understand the ugly errors.
2/15/2002 Joe 155 2/15/2002 Mike 108 2/15/2002 Pete 209 2/22/2002 Joe 158 2/22/2002 Mike 99 2/22/2002 Pete 163 3/1/2002 Joe 172 3/1/2002 Mike 125
#!/usr/bin/perl -w
our %dates;
foreach my $line (<>) {
chomp $line;
my ($this_date, $this_name, $this_score) = split /\s+/, $line;
my ($record_name, $record_score) = split /\|/, $dates{$this_date};
if ($this_name && $this_score) {
if ($this_score > $record_score) {
$dates{$this_date} = join "|", ($this_name, $this_score);
}
}
}
foreach my $date (keys %dates) {
my ($name, $score ) = split /\|/, $dates{$date};
print " The high_scored for $date was $name with $score\n";
shortcasper@shortcasper-laptop:~/perl$ ./hash_bowl bowl_linux Use of uninitialized value in split at ./hash_bowl line 8, line 7. Use of uninitialized value $record_score in numeric gt (>) at ./hash_bowl line 10, line 7. Use of uninitialized value in split at ./hash_bowl line 8, line 7. Use of uninitialized value $record_score in numeric gt (>) at ./hash_bowl line 10, line 7. The high_scored for 3/1/2002 was Joe with 172 The high_scored for 2/15/2002 was Pete with 209 shortcasper@shortcasper-laptop:~/perl$
You should
use warningsinstead of using-w.The reason it complains is that the first time you encounter a particular day,
$dates{$this_date}isundef(because it’s never been set). Splitting that gives you a warning and makes$record_nameand$record_scoreundef(causing your second warning when you compare$this_scoreto$record_score). The code works because numerically,undefis considered 0, but it generates warnings.A simple fix is to use
$dates{$this_date} || '|0'instead. This provides a default value for new dates, setting$record_nameto the empty string and$record_scoreto 0:But you should read the Perl Data Structures Cookbook and consider using a complex data structure instead of having to
joinandsplityour data just to store it in a hash.