Perl将对象数组分配给哈希

时间:2012-08-27 09:51:47

标签: arrays perl hash

我有一个对象数组。

1)我如何迭代它们?

for  my $element (@nodeArray)
{
print $element; 
}

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 ($@);
   $node->id(1);
   $node->name('bob');
   $node->scores(['34','1','1',]);
   unshift(@nodeArray, $node ) ;

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

  unshift(@nodeArray, $node ) ;

print Dumper (@nodeArray); 

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

此外,您可以使用map代替foreach循环

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