Perl 中的 my 和 local 有什么区别? [英] What is the difference between my and local in Perl?

查看:68
本文介绍了Perl 中的 my 和 local 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试调试的脚本中看到它们都使用了,但文献不清楚.有人可以为我揭开这个神秘面纱吗?

I am seeing both of them used in this script I am trying to debug and the literature is just not clear. Can someone demystify this for me?

推荐答案

动态范围.这是一个简洁的概念.很多人不使用它,或者理解它.

Dynamic Scoping. It is a neat concept. Many people don't use it, or understand it.

基本上将 my 视为创建一个变量并将其锚定到一个 {} 块,也就是 A.K.A.范围.

Basically think of my as creating and anchoring a variable to one block of {}, A.K.A. scope.

my $foo if (true); # $foo lives and dies within the if statement.

所以 my 变量是你所习惯的.而动态范围 $var 可以在任何地方声明并在任何地方使用.因此,使用 local 基本上可以暂停使用该全局变量,并使用本地值"来处理它.所以 local 为临时变量创建了一个临时作用域.

So a my variable is what you are used to. whereas with dynamic scoping $var can be declared anywhere and used anywhere. So with local you basically suspend the use of that global variable, and use a "local value" to work with it. So local creates a temporary scope for a temporary variable.

$var = 4;
print $var, "\n";
&hello;
print $var, "\n";

# subroutines
sub hello {
     local $var = 10;
     print $var, "\n";
     &gogo; # calling subroutine gogo
     print $var, "\n";
}
sub gogo {
     $var ++;
}

这应该打印:

4
10
11
4

这篇关于Perl 中的 my 和 local 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆