当前位置:编程学习 > 网站相关 >>

What's the difference between “local” and “my” in Perl

There are two kinds of variable scopes in Perl:

Global variables: They reside in the current package, can be accessed from the outside and can have "local" values. The name can be used as a key in the "stash", the package variable hash / the symbol table.
Lexical variables: They reside in the current scope (roughly delimited by curly braces). There is no symbol table that can be inspected.
Lexical variables and global variables do not interfere, there can be two different variables with the same name.

Most Perl variable magic happens with global variables: These lines are rougly equivalent:

our $var;
$::var;
$main::var;
${var};
${'var'};
local $var;
but not my $var.

So we can write:

@::array = qw(a b c);
my @secondArray = @{array};
Which copies the arrays. We can also look up the array with a name that is stored in a variable:

@::array = qw(a b c);
my $name = "array";
my @secondArray = @{$name};
The last line abbreviates to … = @$name.

This is not possible with lexical vars because they do not reside in the stash.

The local function assigns a "local" value to a global variable (and globals only) within the current scope and in the scope of all subs that are called from within this scope.

Originally (in Perl 4) meddling with variable names and the stash was the only way to simulate references. These usages are now mostly outdated by ~2 decades as references are available (what is far safer).

补充:综合编程 , 其他综合 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,