在符号引用方面,“我的”和“我们的”有什么区别?

时间:2013-03-19 15:46:32

标签: perl

我们的:

our $ref = "test";
my $var = "ref";
print "$$var";   #the output will be test

我:

my $ref = "test";
my $var = "ref";
print "$$var\n"; #the output is blank

1 个答案:

答案 0 :(得分:1)

不同之处在于our会设置一个包变量,而my会设置一个词法变量。

这意味着用our声明的变量可以在当前范围之外访问。

use strict;
use warnings;
{
  our $g = 5;
}
{
  print our($g), "\n";
}
5

虽然词汇变量仅存在于给定范围内。

{
  # stored in this block
  my $l = 5;
  {
    # accessible from this block
    print $l, "\n";
    $l = 6;

    # new variable stored in this lower block
    my $l = 7;
  }
  print $l, "\n";
}
{
  # yet another new variable
  print my($l), "\n";
}
5
6
Use of uninitialized value $a in print at -e line 1.



当您尝试访问$$var时,您使用的是symbolic reference;它只适用于包/全局变量:

our $g = 5;

my $symbolic_ref = 'g';

{
  no strict 'refs';
  # these are symbolic refs
  print $$symbolic_ref, "\n";
  print ${ *{$symbolic_ref} }, "\n";
  print ${ *{$symbolic_ref}{SCALAR} }, "\n";
}

# access it through the magic %:: variable
print ${ $::{$symbolic_ref} }, "\n";
print ${ $main::{$symbolic_ref} }, "\n";
5
5
5
5
5

这与regular references相反。

my $v = 5;

my $ref = \$v;

print $$ref, "\n";
print ${ $ref }, "\n";
5
5

很少有理由使用symbolic reference