使用未初始化的值但声明了变量

时间:2014-03-14 21:02:07

标签: perl if-statement

use strict;
use warnings;
my $last_variable2= 'abc'; 
print "last var2 $last_variable2\n";

my @grouped;

while (<DATA>) {


    my ($variable1, 
        $variable2, 
        $other_data) = split ',',$_,3;

    if($variable2 ne 'abc'){
            if( $variable2 ne $last_variable2){
                   print "\n\n"; 

                   print "'$variable2' doesn't equal '$last_variable2'\n";

                   my %HoA;
                   &process_data(@grouped_series);

                   @grouped = ();

             }
   }else{

       print "Skipped this because it's the first\n";

   }

   push @grouped_series, $_;

   $last_variable2 = $variable2;




}

当我运行此代码时,我一直在

Use of uninitialized value $last_variable2 in string ne at 1_1_correspondencer.pl line 32, <DATA> line 3.
Use of uninitialized value $variable2 in string ne at 1_1_correspondencer.pl line 33, <DATA> line 3.
Use of uninitialized value $last_variable2 in concatenation (.) or string at 1_1_correspondencer.pl line 36, <DATA> line 6.

但是,我初始化了两个变量。抱歉,这是一个天真的问题 - 我刚刚开始使用strictwarnings

1 个答案:

答案 0 :(得分:2)

在解析您的DATA时,您无法验证是否已定义了每个变量:

my ($variable1, 
    $variable2, 
    $other_data) = split ',',$_,3;

如果一行中没有逗号,则$variable2将被取消定义,稍后会将其分配给$last_variable2。也许添加一些数据验证来考虑这种情况?

if (! defined $variable2) {
    warn "missing variable2 definition: $_\n";
}

如果没有看到您的实际数据,我们无法为您提供更多建议。