【问题标题】:Perl : Get the keys of a blessed hashrefPerl:获取祝福的 hashref 的键
【发布时间】:2014-01-17 07:34:53
【问题描述】:

代码中有2个包。

套餐一:

package Foo;
sub new {
    my ($class, $args) = @_;
    my $hashref = {'a' => 1, 'b' => 2};
    bless ($self, $class);
    return $self;
}

包 2:

package Fuz;
use Foo;
.
.
.
.
my $obj = Foo->new($args);

如何获取对象中被祝福的hashref的key?

我知道 perl 中的 Acme::DamnData::Structure::Util 模块可以取消对对象的祝福。还有其他方法可以实现吗?

【问题讨论】:

  • $obj 仍然是 hashref,所以 keys %$obj

标签: perl oop key bless


【解决方案1】:

祝福一个哈希引用并不会改变它仍然是一个哈希引用。因此,您可以像往常一样取消引用它:

my @keys = keys %$obj;

【讨论】:

  • OP 的困惑可能源于最近版本的 Perl 中的自动取消引用功能。 keys($hashref) 有效,而 keys($blessed_hashref) 无效。
【解决方案2】:

首先,您应该use strictuse warnings,因为该代码不会按原样编译。第 5 行的 $self 是什么?你永远不会定义它。修改包代码为:

package Foo;
use strict;
use warnings;
sub new {
    my ($class, $args) = @_;
    my $hashref = {'a' => 1, 'b' => 2};
    bless ($args, $class);
    return $args;
}
1;

现在这将编译,但你想用$hashref 做什么?您是否期望通过$args 传入的参数或者$hashref 可以替换$args?假设确实不需要$args,让我们将其用于Foo

package Foo;
use strict;
use warnings;
sub new {
    my ($class) = @_;
    my $hashref = {'a' => 1, 'b' => 2};
    bless ($hashref, $class);
    return $hashref;
}
1;

现在,当你调用 new 时,你会得到一个祝福的 hashref,你可以从中获取密钥:

> perl -d -Ilib -e '1'

Loading DB routines from perl5db.pl version 1.33
Editor support available.

Enter h or `h h' for help, or `perldoc perldebug' for more help.

main::(-e:1):   1
  DB<1> use Foo

  DB<2> $obj = Foo->new()

  DB<3> x $obj
0  Foo=HASH(0x2a16374)
   'a' => 1
   'b' => 2
  DB<4> x keys(%{$obj})
0  'a'
1  'b'
  DB<5>

【讨论】:

    【解决方案3】:

    你仍然可以在 $obj 上使用键

    my $obj = Foo->new($args);
    my @k = keys %$obj;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-19
      • 2014-07-29
      • 2011-05-04
      • 2011-01-20
      • 2011-10-29
      • 2010-09-28
      • 1970-01-01
      • 2011-11-14
      相关资源
      最近更新 更多