Perl,在循环外使用While循环中的变量?

时间:2010-07-14 09:09:34

标签: perl variables loops scope while-loop

这看起来非常简单,但是由于我不熟悉perl,这让我很难搞清楚。我现在一直在寻找关于循环的大量文档,我仍然对此感到难过......我有一个包含while循环的sub,我想在循环外部的循环中使用一个变量值(在循环运行之后),但是当我尝试打印出变量,或者将它返回到sub时,它不起作用,只有当我从循环中打印变量才能正常工作..我会很感激任何关于我做错的建议。

不起作用(不打印$ test):

sub testthis {    
    $i = 1;
    while ($i <= 2) {    
        my $test = 'its working' ;    
        $i++ ;
    }
    print $test ;
}

&testthis ;

Works,打印$ test:

sub testthis {
    $i = 1;
    while ($i <= 2) {
        my $test = 'its working' ;
        $i++ ;
        print $test ;
    }
}

&testthis ;

3 个答案:

答案 0 :(得分:9)

在循环中声明变量测试,因此它的作用域是循环,一旦离开循环,变量就不再声明了。
my $test;$i=1之间添加while(..)即可。范围现在将是整个子而不是仅循环

答案 1 :(得分:5)

在while循环之前放置my $test。请注意,它仅包含在while循环中分配的最后一个值。这就是你追求的目标吗?

// will print "it's working" when 'the loop is hit at least once,
// otherwise it'll print "it's not working"
sub testthis {
    $i = 1;
    my $test = "it's not working";

    while ($i <= 2) {
        $test = "it's working";
        $i++ ;
    }
    print $test ;
}

答案 2 :(得分:3)

你可以尝试这个:

sub testthis {
my $test
$i = 1;
while ($i <= 2) {

$test = 'its working' ;

$i++ ;

print $test ;
}

}

&amp; testthis;

注意:每当编写perl代码时,最好在代码的开头添加use strict;use warning

相关问题