0

I have an array of objects.

1)How can I iterate through them?

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

2)How can I place each element in the array into a hash.The key for each element will be $node->id(); the value for each node element will be the properties of the object. So $node->id() will be repeated.

Code is here:

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); 
4

2 回答 2

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

print Dumper(\%hash), "\n";
于 2012-08-27T09:56:56.647 回答
1

您也可以使用map而不是foreach循环

my %hash = map {
    $_->id() => {
        id => $_->id(),
        name => $_->name(),
        scores => [$_->scores()]
    }
} @nodeArray;
于 2012-08-27T10:32:52.313 回答