【问题标题】:PERL | Blessed object in hash | Rose::DB::Object珀尔 |哈希中的受祝福对象 |玫瑰::DB::对象
【发布时间】:2012-08-02 21:46:43
【问题描述】:

我试图弄清楚为什么我无法访问元素内部的祝福引用:

这是我的模块:

package Test::Node

__PACKAGE__->meta->setup(
    table   => 'node',

    columns => [
        id                             => { type => 'serial', not_null => 1 },
        name                           => { type => 'varchar', length => 128, not_null => 1 },
    ],

    primary_key_columns => [ 'id' ],

    relationships =>
    [ 
      alias =>
      { 
        type       => 'one to many',
        class       => 'Test::Alia',
        column_map => { id => 'asset_id' },
      },
],

这是我要测试的子:

sub SearchNode {
  my $self = shift;
  my ($opts) = shift;
  my %query = (name => { like => "$opts->{name}%"});
  my %object = (with_objects => ['alias']);
  $object{query} = [%query] if $opts->{name};

  my $records = Test::Node::Manager->get_node(%object);
  my $i = 0;  
  my $record = {}; 
  $record->{page} = 1;
  $record->{total} = 1;
  foreach (@$records) {
    my %items =(
      id => $_->id,
      name => $_->name,
      alias => $_->alias->alias
    );  
    $record->{rows}[$i] = \%items; 
    $i++;
  }   
  $record->{records} = $i; 
  return $record;
}

如果我使用 $_->alias,我会返回以下内容:

$ ./search.pl 
$VAR1 = {
          'page' => 1,
          'records' => 1,
          'rows' => [
                      {
                        'name' => 'test.localhost.net',
                        'id' => '1234',
                        'alias' => bless( {
                                            'node_id' => '1234',
                                            'id' => '5678',
                                            'alias' => 'server1.localhost.net'
                                          }, 'Test::Alia' )
                      }
                    ],
          'total' => 1
        };

如果我使用 $_->alias->alias,我会收到一个错误:

./search.pl 
Can't call method "alias" on unblessed reference at /usr/local/lib/perl/Test/Node.pm line 41.

我有点困惑,因为 Dumper 输出显示 Alias 的值是有福的,这似乎与错误消息相矛盾。

【问题讨论】:

    标签: perl rose-db-object


    【解决方案1】:

    Dumper 输出显示 $_->alias 返回一个哈希引用,而不是一个对象。要访问结构中的别名对象,您需要以下内容:

    $_->{rows}[0]{alias};
    

    访问该对象的别名方法:

    $_->{rows}[0]{alias)->alias;
    

    【讨论】:

    • $_ 标准变量正在 foreach 循环中使用。如果我能够使用 $_->name 访问 foreach 中的其他属性,为什么别名不起作用?
    猜你喜欢
    • 2017-09-25
    • 2013-05-04
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2014-07-24
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多