【问题标题】:Perl, using variable from within While loop outside of the loop?Perl,在循环外使用While循环内的变量?
【发布时间】:2010-07-14 09:09:33
【问题描述】:

这看起来很简单,但我很难弄清楚,因为我是 perl 的新手。我现在一直在浏览很多关于循环的文档,但我仍然对此感到困惑......我有一个包含 while 循环的子程序,我想在循环外的循环内使用变量值(在循环运行后),但是当我尝试打印出变量或将其从子程序中返回时,它不起作用,只有当我从循环中打印变量时它才会起作用。我将不胜感激任何关于我做错了什么的建议。

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

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

&testthis ;

工作,打印 $test:

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

&testthis ;

【问题讨论】:

  • $i = 1; 应该是my $i = 1;,现在的方式是,您正在与外部范围内的变量$i 交谈,一旦您开始,这将成为错误的来源从其他子程序内部调用子程序。很有可能$i 甚至没有在外部作用域中声明,在这种情况下,您正在与包变量对话。如果你在use strict; use warnings; 下运行,那么strict 杂注会抛出关于未声明变量的错误。

标签: perl variables loops scope while-loop


【解决方案1】:

你在循环内声明变量 test,所以它的作用域就是循环,一旦你离开循环,变量就不再被声明了。
$i=1while(..) 之间添加my $test; 就可以了。范围现在将是整个 sub 而不仅仅是循环

【讨论】:

  • 啊,好的,我现在明白了.. 谢谢... 我一直在看的教程太基础了,甚至没有提到这一点,我想我应该直接去 perl 手册页现在开始
【解决方案2】:

my $test 放在while 循环之前。请注意,它将仅包含在 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多