Gossamer Forum
Home : Products : Gossamer Links : Version 1.x :

How to access an element from fetchall_arrayref

Quote Reply
How to access an element from fetchall_arrayref
Does anyone know how I can access a particular element retrieved from
$att_r = $get_att->fetchall_arrayref
Did I ask that right? This is what I'm trying to do.

I've successfully setup an sql query that looks into the attachment database and pulls out all the dataids for links in a particular category. That's this code:

$get_att = $LINKDB->prepare (" SELECT l.ID FROM Artisans_Attach as l, Artisans as c WHERE l.DataID = c.ID AND c.CategoryID = ?");

then I execute it:
$get_att->execute ($category_r->{'ID'});
and read it into $att_r
$att_r = $get_att->fetchall_arrayref || []; #Get list of attachments

Now I'm trying to randomly access one of the ids this way (ultimately I want to access more than one, but I have to get through this part first.
my @attx = (@{$att_r});
my $randomnumber = int rand(@attx);
print "my random number is $randomnumber \n";

sample result: my random number is 3

$randomnumber appears to represent the location of the DataID within the array as opposed to the actual DataID.
for example. My sql query will bring back this list 1, 12, 15, 45, 98 but my $randomnumber only comes back as 0,1,2,3,4,5. This suggests the location within the array.

So with that number I'm trying to access the Value of $attx[$randomnumber] like you normally would with an array with:

my $dataid = $attx[$randomnumber];
print "my dataid is $dataid";


but it always comes back with results like this:
my dataid is ARRAY(0x83bee5c) - I don't get why this is the return value

It seems like the information that gets stored in $att_r has a different format than one would normally expect from an array and I'm not accessing it properly and I have tried everything I can think of.

What am I doing wrong ? or is there an easier way of doing this.

Peace.

Kyle



Quote Reply
Re: How to access an element from fetchall_arrayref In reply to
You see that because it's an array of arrays. Looks like:

my $results =
[
['1', 'Title, 'Description'],
['2', 'NewTitle', 'NewDescription'],
['3', 'etc', 'you get the idea'],
...
];

So to get a random array, you could do:

my $random = $results->[int rand $#results];

You now have a random result as an array ref. You can either:

my $hash = $db->array_to_hash($random);

and now have it as a hash, or you can get a specific field if you know the position, you could get:

my $id = $random->[0];

assuming id is in position 0.

Hope this helps,

Alex

--
Gossamer Threads Inc.