Perl 中的全局变量、子程序变量问题
如何将子程序变量值转移到另一个子程序变量中,我可以使用全局变量吗?
sub foo(){
my $myvar = "Hello";
}
sub foo1(){
my $myvar1 = $myvar; # how can I get the "Hello" from $myvar.
}
我尝试使用包和全局变量,但失败了。
Package Bar;
our $bar;
谢谢。
How can I transfer the subroutine variable value into another subroutine variable, Can I use global variable.
sub foo(){
my $myvar = "Hello";
}
sub foo1(){
my $myvar1 = $myvar; # how can I get the "Hello" from $myvar.
}
I tried to use package and global variable, but failed.
Package Bar;
our $bar;
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在包含 2 个函数的作用域中声明变量:
但这并不是很优雅,并且可能很难维护,因为在
foo1
中不清楚$ 的值在哪里myvar
已设置。将变量作为参数传递可能更好。请注意,所有 3 个
$myvar
都是不同范围内的不同变量。附带说明一下,使用原型 (
sub foo()
) 可能不是一个好主意,除非您真的知道它们在做什么,但情况可能并非如此(请参阅 原型的问题用于原型的讨论)You could declare the variable in a scope that includes the 2 functions:
That is not really elegant though, and can be hard to maintain, as it is not clear in
foo1
where the value of$myvar
was set. It is probably better to pass the variable as an argument.Note that all 3
$myvar
are different variables, in different scopes.As a side note, using prototypes (
sub foo()
) is probably not a good idea, unless you really know what they are doing, which is likely not to be the case ( see The problem with prototypes for a discussion on prototypes)是的,您可以:
即使使用“use strict;”,这也有效。和“使用警告;”。
包变量适用于您想要导出到包外部的变量,而不是您想要在同一包中的两个子例程之间共享的变量。
Yes, you can:
This works even with "use strict;" and "use warnings;".
Package variables are for variables you want to export outside your package, not for variables you want to share between two subroutines in the same package.
只是不要使用
my
:但是,我不推荐这种编程方式。
Just don't use
my
:However, I don't recommend this way of programming.
你有几种方法。
最简单的就是不使用
my
声明变量。但这要求您避免use strict;
,因此不建议这样做。您可以在脚本顶部的函数外部声明变量。然后这个变量将可用于下面的所有函数。这是 scope 的结果:在一组大括号之外声明的变量是通常可在任何后续花括号内使用。
您可以使用
use vars qw/$myvar/;
编译指示来声明变量。这本质上使您的变量在以下代码中可用。You have a few approaches.
The simplest is not to declare the variable with
my
. But this requires you to avoiduse strict;
and not recommended as a result.You could declare your variable outside the functions at the top of your script. This variable would then be available to all functions below. This is a consequence of scope: variables declares outside a set of curly braces are generally available inside any subsequent curly braces.
You could declare your variable using the
use vars qw/$myvar/;
pragma. This inherently makes your variable available throughout the following code.以下代码可以演示您所描述的解决方案:
结果应该是:
The following code may demonstrate a solution to what you describe:
The result should be: