PerlMonks =),
I'm playing with an 'array of hashes of arrays' and having some problems with data manipulation and was wondering if there might be some incite from above to help out...
We have the following data structure,
List (array of things)
|->hash of data about things (name, inputs, outputs)
|->some data elements require arrays of data. (can have multiple inputs and outputs)
In the following code the
AddConnection subroutine works fine and pushes the
$from and
$to variables into the arrays of the hash of object properties, which belongs to an array of objects.
sub AddConnection {
my ($from, $to) = @_;
for $l ( @list ) {
if ( $l->{"name"} eq $from ) {
push @{$l->{"outputs"}}, $to;
}
if ( $l->{"name"} eq $to ) {
push @{$l->{"inputs"}}, $from;
}
}
}
sub AddRandomConnection {
my @arr;
my $i = scalar(@inputlist);
print "we have $i elements to choose from\n";
my $rand_i = int(rand($i));
my $from = $inputlist[$rand_i];
print "we picked $rand_i : $from\n";
my $o = scalar(@inputlist);
print "we have $i elements to choose from\n";
my $rand_o = int(rand($o));
my $to = $outputlist[$rand_o];
print "we picked $rand_o : $to\n";
#TODO: need to make sure you can't come to and from same node
for $l ( @list ) {
if ( $l->{"name"} eq $from ) {
push @{$l->{"outputs"}}, $to;
}
if ( $l->{"name"} eq $to ) {
push @{$l->{"inputs"}}, $from;
}
}
}
The issue comes with the second function
AddRandomConnection which employs the same code to access the data, but returns the following error upon execution.
we have 2 elements to choose from
we picked 0 : O1
we have 2 elements to choose from
we picked 1 : I2
Modification of a read-only value attempted at <myfile> line 73.
As can be seen the error message eludes to accessing bad data or some such, but the selection of elements 0 and 1 are within the limits of the array size of two for each element.
Can anyone see my oversight?
Regards Paul =)
Edit by castaway - Added readmore tags
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.