如何创建Perl别名?类型问题?

时间:2018-06-25 07:39:54

标签: perl alias perl-module

假设我正在处理另一个包中的哈希,并且想为该变量创建别名?有什么干净的方法可以做到这一点?此示例代码显示了我想要执行的操作,但是它以及它的许多变体都无法正常工作。

#!/usr/bin/perl
#use strict;  # I want it to work with strict.

my $p = Person->new("Joe");
my $name;
*name = \*$p->{"name"};     # Latest broken attempt

printf("'%s' should eq '%s' because they both point to the same place.\n",
       $name, $p->{"name"});

$name = "Sam";

printf("'%s' should eq '%s' because they both point to the same place.\n",
       $name, $p->{"name"});
exit 0;


package Person;

sub new {
    my $class = shift;

    my $this = {};
    bless $this, $class;

    $this->{"name"} = shift;

    return $this;
}

我想要的功能是能够操作$p->{"name"}数十次而不必重复键入$p->{"name"}。真正的数据结构要复杂得多,有很多嵌套的哈希。

这可能很容易。 谢谢。

1 个答案:

答案 0 :(得分:6)

最简单的方法是制作副本:

use strict;
use warnings;
my $p = { name => "Joe" };
my $name = $p->{name};
print "'$name' is '$p->{name}'\n";

如果不需要分配给$name,这就是我要使用的。

如果您希望能够通过$name进行书写,最简单的方法是使其成为参考:

use strict;
use warnings;
my $p = { name => "Joe" };
my $name = \$p->{name};
print "'$$name' is '$p->{name}'\n";
$$name = "Jill";
print "'$$name' is '$p->{name}'\n";

如果您确实想要别名,最简单的方法是滥用for循环:

use strict;
use warnings;
my $p = { name => "Joe" };
for my $name ($p->{name}) {
    print "'$name' is '$p->{name}'\n";
    $name = "Jill";
    print "'$name' is '$p->{name}'\n";
}

如果您的perl足够新(5.22+),您还可以通过引用进行别名:

use strict;
use warnings;
use feature 'refaliasing';
my $p = { name => "Joe" };
\my $name = \$p->{name};
print "'$name' is '$p->{name}'\n";
$name = "Jill";
print "'$name' is '$p->{name}'\n";

最后,您可以通过分配给typeglob来对变量进行别名化,但这并不是我在这里实际使用的东西:

use strict;
use warnings;
my $p = { name => "Joe" };
*name = \$p->{name};  # sets *name{SCALAR} to point to $p->{name}
our $name;            # declares $name so we can use it to refer to $main::name
print "'$name' is '$p->{name}'\n";
$name = "Jill";
print "'$name' is '$p->{name}'\n";