我试图找出为什么我无法访问元素内部的祝福引用:
这是我的模块:
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;
}
如果我使用$ _->别名,我会收到以下内容:
$ ./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的值是有福的,这似乎与错误消息相矛盾,所以我很困惑。
答案 0 :(得分:1)
Dumper输出显示$_->alias
返回hash-ref,而不是对象。要访问结构中的别名对象,您需要以下内容:
$_->{rows}[0]{alias};
要访问该对象的别名方法:
$_->{rows}[0]{alias)->alias;