-1

我们的:

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
4

1 回答 1

1

The difference is that our will set up a package variable, while my sets up a lexical variable.

What that means is that variables declared with our can be accessed outside of the current scope.

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

While lexical variables exist only in a given scope.

{
  # 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.



When you were trying to access $$var you were using a symbolic reference; which only work on package/global variables:

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

That is opposed to regular references.

my $v = 5;

my $ref = \$v;

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

There is rarely any reason to use a symbolic reference.

于 2013-03-20T20:37:04.027 回答