9

在 Perl 中,以下两种结构之间是否有任何区别:

*main::foo = *main::bar

$main::{foo} = $main::{bar}

它们似乎具有相同的功能(将所有插槽别名为 中*main::foo定义的插槽*main::bar),但我只是想知道这种等效性是否始终成立。

4

4 回答 4

9

*main::foo也许不是您要寻找的那种差异,但是和之间有两个很大的差异$main::{foo};前者在编译时在 stash 中查找 glob,如有必要则创建它,而后者在运行时在 stash 中查找 glob,并且不会创建它。

这可能会对隐藏中的任何其他内容产生影响,并且肯定会影响您是否收到used only once警告。

于 2011-07-07T03:56:25.120 回答
3

访问 stash as$A::{foo} = $obj允许您在符号表上放置任何内容,同时根据类型*A::foo = $obj放置在 typeglob 的预期插槽上。$obj$obj

例如:

  DB<1> $ST::{foo} = [1,2,3]

  DB<2> *ST::bar = [1,2,3]

  DB<3> x @ST::foo
Cannot convert a reference to ARRAY to typeglob at (eval 7)[/usr/local/perl/blead-debug/lib/5.15.0/perl5db.pl:646] line 2.
 at (eval 7)[/usr/local/perl/blead-debug/lib/5.15.0/perl5db.pl:646] line 2
    eval '($@, $!, $^E, $,, $/, $\\, $^W) = @saved;package main; $^D = $^D | $DB::db_stop;
  @ST::foo;

;' called at /usr/local/perl/blead-debug/lib/5.15.0/perl5db.pl line 646
    DB::eval called at /usr/local/perl/blead-debug/lib/5.15.0/perl5db.pl line 3442
    DB::DB called at -e line 1
  DB<4> x @ST::bar
0  1
1  2
2  3
  DB<5> x \%ST::
0  HASH(0x1d55810)
   'bar' => *ST::bar
   'foo' => ARRAY(0x1923e30)
      0  1
      1  2
      2  3
于 2011-07-07T00:57:26.367 回答
3

以下脚本:

#!/usr/bin/env perl

#mytest.pl

no warnings;


$bar = "this";
@bar = qw/ 1 2 3 4 5 /;
%bar = qw/ key value /;

open bar, '<', 'mytest.pl' or die $!;

sub bar {
    return "Sub defined as 'bar()'";
}
$main::{foo} = $main::{bar};

print "The scalar \$foo holds $foo\n";
print "The array \@foo holds @foo\n";
print "The hash \%foo holds ", %foo, "\n";
my $line = <foo>;
print "The filehandle 'foo' is reads ", $line;
print 'The function foo() replies "', foo(), "\"\n";

输出:

The scalar $foo holds this
The array @foo holds 1 2 3 4 5
The hash %foo holds keyvalue
The filehandle 'foo' is reads #!/usr/bin/env perl
The function foo() replies "Sub defined as 'bar()'"

因此,如果*main::foo = *main::bar;不做与 相同的事情$main::{foo} = $main::{bar};,我不知道如何检测实际差异。;) 但是,从语法的角度来看,可能存在使用一种方法比使用另一种方法更容易的情况。...关于在符号表中乱七八糟的常见警告始终适用。

于 2011-07-06T23:45:12.527 回答
0

另请参阅“标量与 glob(*{} 不应返回 FAKE glob)”

https://github.com/perl/perl5/issues/10625

于 2019-12-22T12:22:48.093 回答