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

Ric*_*ick 6 variables perl scope loops while-loop

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

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

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

&testthis ;
Run Code Online (Sandbox Code Playgroud)

Works,打印$ test:

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

&testthis ;
Run Code Online (Sandbox Code Playgroud)

rad*_*ius 9

你在循环中声明了变量test,所以它的作用域就是循环,只要你离开循环就不再声明变量.只需在和之间
添加my $test;即可.范围现在将是整个子而不是仅循环$i=1while(..)

  • 啊好吧,我现在明白了......谢谢......我一直在看的教程太基础了,甚至没有提到过这个,我想我应该从现在开始直接进入perl手册页 (2认同)

Abe*_*bel 5

my $testwhile循环之前.请注意,它仅包含在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 ;
}
Run Code Online (Sandbox Code Playgroud)