在Perl中,如何在子例程之间共享变量,使用严格?

前端之家收集整理的这篇文章主要介绍了在Perl中,如何在子例程之间共享变量,使用严格?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我不使用严格;以下代码工作正常并打印出“alice”:

assign_name();
print_name();

sub assign_name {
    $name = "alice";
}

sub print_name {
    print $name;
}

但是当我使用严格;然后我知道我必须在使用之前声明变量.我读到某个地方我应该使用我们而不是我来声明一个全局变量.所以我有以下几点:

use strict;
use warnings;

assign_name();
print_name();

sub assign_name {
    our $name = "alice";
}

sub print_name {
    print $name;   # This is line 12.

}

然后我收到以下错误

Variable "$name" is not imported at test.pl line 12.
Global symbol "$name" requires explicit package name at test.pl line 12.
Execution of test.pl aborted due to compilation errors.

请帮忙.

解决方法

只需声明变量,两个潜艇都可以看到它.

use strict;
use warnings;

my $name;

assign_name();
print_name();

sub assign_name {
    $name = "alice";
}

sub print_name {
    print $name;
}

(我没有理由在这里使用!)

猜你在找的Perl相关文章