变量需要if语句中的显式包名

时间:2016-04-05 11:56:21

标签: perl

我编写了一个Perl子例程,该子例程应该采用一个月的名称,如果匹配则返回一个数字,否则返回原始参数。

sub convert_month_to_number {
 my ($input) = @_;
 my @month_names = qw/January February March April May June July August September October November December/;
 my @month_names_short = qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;
 for (my $i = 0; $i < scalar(@month_names); $i = $i + 1){
    print "$month_names[$i]\n";
    if ($input == $month_names[$i]{
        return $i;

    }   
 }

return $input;  
}

}

但是,在Padre中编译时,我收到错误:

syntax error at additionalscripts.pl line 16, near "}"
Global symbol "$input" requires explicit package name at additionalscripts.pl li
ne 19.
syntax error at additionalscripts.pl line 20, near "}"
Execution of additionalscripts.pl aborted due to compilation errors.

我不确定为什么会发生这种情况,考虑到我已经将$ input声明为全局变量。任何帮助将不胜感激。我目前在Windows上使用Perl 5.010。

1 个答案:

答案 0 :(得分:0)

您的代码中有一些错误,我已经清理过了。

my @test = qw(Foo January Bar);
say convert_month_to_number($_) foreach @test;

sub convert_month_to_number {
    my ($input) = shift;
    my @month_names = qw/January February March April May June July August September October November December/;
    my @month_names_short = qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;

    for (my $i = 0; $i < @month_names; $i++){
        if ($month_names[$i] eq $input){
            return $i;
        }

    }
    return $input; 

}