Perl 中的词法范围和动态范围有什么区别? [英] What is the difference between lexical and dynamic scoping in Perl?

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

问题描述

据我所知,my 运算符用于声明真正具有词法作用域的变量,而动态作用域则是使用 local 运算符来声明变量.>

谁能简单介绍一下?

解决方案

local($x) 保存全局变量 $x 的旧值并为子程序的持续时间分配一个新值在从该子程序调用的其他函数中可见.这个完成了在运行时,因此称为动态范围.local() 总是影响全局变量,也称为包变量或动态变量.

my($x) 创建一个新变量,该变量仅在当前子程序.这是在编译时完成的,因此称为词法或静态范围.my() 总是影响私有变量,也称为词法变量或(不正确的)静态(限定范围的)变量.

看看 Perl 常见问题解答:

As far I know, the my operator is to declare variables that are truly lexically scoped and dynamic scoping is done using the local operator to declare a variable.

Can any one describe them in brief?

解决方案

local($x) saves away the old value of the global variable $x and assigns a new value for the duration of the subroutine which is visible in other functions called from that subroutine. This is done at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables.

my($x) creates a new variable that is only visible in the current subroutine. This is done at compile-time, so it is called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.

Take a look at the Perl-FAQ's:

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

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