spatterson has asked for the wisdom of the Perl Monks concerning the following question:

*update* Thanks ikegami, that sorted it
I have some code with a couple of different classes. One element of object A is an array populated on-the-fly with multiple objects of class B
class A constructor: (roughly)
my $A = {}; bless $A, 'class A'; $A->{arrayholder} = qw//; return $A
later on in another method of class A which works, $B1 & $B2 are defined correctly
my $B1 = B->new(); my $B2 = B->new(); my @Bees; push @Bees, $B1, $B2;
Then class A calls a method on every class B object it contains
foreach my $B ($A->{arrayholder}) { print Dumper $B; print $B->Bfoo; }
Which fails with 'cannot call method Bfoo without a package or object reference' and the Dumper line prints the count of $B items (scalar $A->{arrayholder})
So how can I pull the B objects out of the array to run a method on each?

just another cpan module author

Replies are listed 'Best First'.
Re: How to store and retreive an array of items from within a hashref
by ikegami (Patriarch) on Jul 20, 2007 at 13:47 UTC

    It's not printing scalar $A->{arrayholder}), it's printing the scalar value of whatever was assigned to $A->{arrayholder}, since hash elements (incl $A->{arrayholder}) are always scalars.

    If you wish to store a list in a hash element, create an array containing the list and store a reference to that array in the hash element. (References are scalars.)

    $A->{arrayholder} = [ ]; @{ $A->{arrayholder} } = ( $B1, $B2 ); # -or- #push @{ $A->{arrayholder} }, $B1, $B2; foreach my $B (@{ $A->{arrayholder} }) { ... }

    Update: Rephrased text to be a bit clearer.

Re: How to store and retreive an array of items from within a hashref
by lima1 (Curate) on Jul 20, 2007 at 13:52 UTC
    Is
    $A->{arrayholder}
    really an arrayref with objects? Can't see it in your code...
    $self->{arrayholder} = \@bees
    Then you must dereference the arrayref:
    foreach my $B (@{ $A->{arrayholder} } ) { .. }
Re: How to store and retreive an array of items from within a hashref
by FunkyMonk (Bishop) on Jul 20, 2007 at 14:54 UTC
    $A->{arrayholder} = qw//;
    Assigns undef to $A->{arrayholder}. You probably want to assign an empty anonymous arrayref:

    $A->{arrayholder} = [];

    push @Bees, $B1, $B2;
    This pushes your B's on to the array @Bees, but you don't do anything with it! Surely you can get rid of this array and just do:

    push @{ $A->{arrayholder} }, $B1, $B2;