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

2 Answers 2

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

print Dumper(\%hash), "\n";
Sign up to request clarification or add additional context in comments.

Comments

1

Also you can use map instead of foreach loop

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.