Eric Lease Morgan wrote:


How do I manipulate array references?

In a package I'm writing I initialize an array reference (I think) through DBI like this:

$self->{author_ids} = $dbh->selectall_arrayref($query);


This gets tricky because selectall_arrayref returns an reference to an array. Each value of that array is a reference to an array as well.

$self->{author_ids} is a reference to an array whose elements are in fact references to arrays (that contains scalars thank goodness).

@{$self->{author_ids}} is the array.
$#{$self->{author_ids}} is the number of elements in the array.

@{$self->{authors_ids}->[0]} is the first row of data (an array).
$#{$self->{authors_ids}->[0]} is the number of columsn in the first row of data.



$self->{author_ids}->[0] is a reference to an array representing one row of data.
$self->{author_ids}->[0]->[0] would be the first field of the first row of data.



First of all, what sort of foreach loop can I write to iterate through the contents of $self->{author_ids}?

foreach $i (0..$#{$self->{authors_ids}}) { foreach $j (0..$#{$self->{authors_ids}->[$i]}) { print $self->{authors_ids}->[$i]->[$j]; } print "\n"; }


Second, how do I undefine the value of $self->{author_ids}?


$self->{author_ids} = undef;


Third, if I have a list of integers, how to I assign the items in this list to $self->{author_ids}?


$self->{author_ids}->[0] = 1;
$self->{author_ids}->[1] = 2;
$self->{author_ids}->[2] = 3;

or

$self->{author_ids} = [1, 2, 3];

Or if you want something similar to what selectall_arrayref() is producing:

$self->{author_ids} = [ [1,2,3], [3,7,9], [2,8,4]];

Which could be printed like so:

foreach $i (0..$#{$self->{authors_ids}}) {
   foreach $j (0..$#{$self->{authors_ids}->[$i]}) {
       print $self->{authors_ids}->[$i]->[$j];
   }
   print "\n";
}


I would strongly recommend adding quotation marks to {authors_ids} so that it is {'authors_ids'} or defining it as a constant. The only reason why {authors_ids} is equivalent to {'authors_ids'} is because PERL is converting it to a constant on the fly for you. If you accidentally picked a name that was already a constant in your namespace you might end up with results that are hard to debug (imagine if a module put a constant in your name space that you didn't know about).


--
Michael McDonnell, GCIA
Winterstorm Solutions, Inc.
[EMAIL PROTECTED]

Reply via email to