首页 文章

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

提问于
浏览
6

这看起来很简单,但是由于我是新手,我很难搞清楚它 . 我现在一直在查看关于循环的大量文档,我仍然对此感到困惑...我有一个包含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 回答

  • 5

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

  • 9

    在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 ;
    }
    
  • 3

    你可以尝试这个:

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

    &testthis;

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

相关问题