perl未初始化的值...错误

时间:2011-10-23 05:02:08

标签: perl

我继续在use strict上使用strict来获取初始化错误,并且无法找出原因。我为所有变量设置了范围 - 并且代码运行。只是不明白丑陋的错误。

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$

3 个答案:

答案 0 :(得分:6)

您应该use warnings而不是-w

它抱怨的原因是,当您第一次遇到某一天时,$dates{$this_date}undef(因为它从未设置过)。拆分会给您一个警告并生成$record_name$record_score undef(在您将$this_score$record_score进行比较时会发出第二次警告)。代码可以正常工作,因为数字undef被认为是0,但它会生成警告。

一个简单的解决方法是使用$dates{$this_date} || '|0'代替。这为新日期提供了默认值,将$record_name设置为空字符串,将$record_score设置为0:

use strict;
use warnings;

our %dates;
foreach my $line (<DATA>) {
    chomp $line;
    my ($this_date, $this_name, $this_score) = split /\s+/, $line;
    my ($record_name, $record_score) = split /\|/, $dates{$this_date} || '|0';
    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";
}

__DATA__
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

但您应该阅读Perl Data Structures Cookbook,并考虑使用复杂的数据结构,而不是只需将joinsplit数据存储在哈希值中。

答案 1 :(得分:2)

在我看来,您的哈希%dates已初始化但其值不是。您的代码在实际设置之前尝试使用$dates{$this_date}的值(稍后会发生几行)。

答案 2 :(得分:0)

%date是一个空哈希。所以$ dates {$ this_date}正在变成“undef”

改变你的内心状况,使其发挥作用;当没有旧记录时,它将插入日期哈希。

 if ( !(defined  $record_score) || $this_score > $record_score) {
                $dates{$this_date} = join "|", ($this_name, $this_score);
        }