2012-08-01 57 views
1

我試圖弄清楚爲什麼我不能元素的內部訪問一個祝福參考:PERL |散列中的祝福對象|玫瑰:DB:對象

這是我的模塊:

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->別名,我收到一個錯誤:

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

我升技混淆,因爲泥頭輸出顯示別名的值被祝福這似乎違背了錯誤信息。

回答

1

Dumper輸出顯示$_->alias返回一個散列引用,而不是一個對象。結構內部訪問別名對象,你需要的東西,如:

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

訪問該對象的別名法:

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

的$ _標準變量被foreach循環中使用。如果我能夠使用$ _->名稱訪問foreach中的其他屬性,爲什麼別名不起作用? – user1566958 2012-08-02 16:43:17

+0

$ _-> [0] - >別名的作品 – user1566958 2012-08-03 05:15:15