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;
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.