PERL|hash中的祝福对象|Rose::DB::object



我试图弄清楚为什么我不能访问元素内部的幸运引用:

这是我的模块:

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的值是幸运的,这似乎与错误消息相矛盾。

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

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

访问该对象的别名方法:

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

最新更新