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

I have a couple of situations where I'm trying to store data as objects and then pass the data on to another subroutine. My data structures end up becoming a bit complicated and I'm having trouble retrieving the data. Below is a simplified example where I'm inventorying batches documents by volume and page ranges. Along the way I also need to look for page gaps. What I've done is created an object called batch_inventory with the elements ranges and gaps. The ranges element will be an array of page_range objects. Each "page_range" object contains "volume", "start page" and "end page" elements. For simplicity's sake I'm just assigning numeric values to each element of the page_range object. Example code is below. When I execute the code I get the error: Can't use string ("3") as a HASH ref while "strict refs" in use at obj_test.pl line 21. It looks like trying to access an array of hashes results in the structure being collapsed into a single long array. I can't seem to figure out a way to make this work. If at all possible, I need to make these data structures work without altering my overall process.
#!/usr/bin/perl use strict; use warnings; my $inv = batch_inventory->new(); my @ranges; for (my $c = 1; $c < 9; $c+= 3) { my $range = page_range->new(); $range->{vol} = $c; $range->{start_pg} = $c+1; $range->{end_pg} = $c+2; push (@ranges,$range); } $inv->{ranges} = @ranges; foreach my $range ($inv->{ranges}) { print "$range->{vol} $range->{start_pg} $range->{end_pg}\n"; } exit (0); ########## Objects ########## package page_range; sub new { my $class = shift; my $self = { vol => undef, start_pg => undef, end_pg => undef }; bless $self, $class; return $self; } package batch_inventory; sub new { my $class = shift; my $self = { ranges => undef, gaps => undef }; bless $self, $class; return $self; }

Replies are listed 'Best First'.
Re: Arrays/Lists of Hashes
by kyle (Abbot) on Mar 16, 2009 at 21:40 UTC
Re: Arrays/Lists of Hashes
by almut (Canon) on Mar 16, 2009 at 21:55 UTC

    As kyle explained, you want

    $inv->{ranges} = \@ranges;

    And, in order to then iterate over $inv->{ranges} in your foreach loop, you'll also need to dereference it, like this:

    foreach my $range ( @{$inv->{ranges}} ) { ... }