2012-08-27 116 views
0

我有一個對象數組。Perl將一個對象數組分配給一個散列

1)我如何遍歷它們? 2)如何將數組中的每個元素放入哈希中。每個元素的鍵都是$ node-> id();每個節點元素的值將是對象的屬性。所以$ node-> id()會重複。

代碼是在這裏:

package person; 
sub new { 
     my ($class) = @_; 
     my $self = { 
      _id => undef, 
      _name => undef, 
      _scores => [] 
        }; 
    bless $self, $class; 

     return $self; 
} 

sub id{ 
    my ($self, $id) = @_; 
    $self->{_id} = $id if defined($id); 
    return $self->{_id}; 
    } 

    sub name{ 
    my ($self, $name) = @_; 
    $self->{_name} = $name if defined($name); 
    return $self->{_name}; 
    } 

    sub scores { 
     my ($self, @scores)= @_; 
     if (@scores) { 
      @{ $self->{_scores} } = @scores; 
      }; 
     return @{ $self->{_scores} }; 
    } 

use strict; 
use warnings; 

#use person; 
use Data::Dumper; 
my @nodeArray=undef ; 
my %hash = undef; 



my $node = eval{person->new();} or die ([email protected]); 
    $node->id(1); 
    $node->name('bob'); 
    $node->scores(['34','1','1',]); 
    unshift(@nodeArray, $node) ; 

    $node = eval{person->new();} or die ([email protected]); 
    $node->id(2); 
    $node->name('bill'); 
    $node->scores(['3','177','12',]); 

    unshift(@nodeArray, $node) ; 

print Dumper (@nodeArray); 

回答

3
foreach my $n (@nodeArray) { 
    $hash{$n->id()} = { 
    name => $n->name(), 
    id  => $n->id(), 
    scores => [$n->scores()] 
    }; 
} 

print Dumper(\%hash), "\n"; 
1

您也可以使用map代替foreach

my %hash = map { 
    $_->id() => { 
     id => $_->id(), 
     name => $_->name(), 
     scores => [$_->scores()] 
    } 
} @nodeArray; 
相關問題