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