Ok – I have the following member function.
sub GetCategories {
my $sth = $dbh->prepare("SELECT CatID, CatName, CatLink FROM Categories");
$sth->execute() or die $DBI::errstr;
my $results = $sth->fetchall_arrayref({});
return($results);
` $sth->finish();
}
I call it with:
my $Cats = $d2s->GetCategories();
my $vars = my $vars = {
categories => $Cats,
};`
`
However my question is, how do I drill through that and extract the values in perl?
It is driving me nuts – below is the format of the $vars data from Data::Dumper –
$VAR1 = {
'categories' => [
[
1,
'General',
'./PostList.pl?cat=General'
],
[
2,
'DevOps',
'./PostList.pl?cat=DevOps'
]
};
I expected to see
'categories' => [ { 'CatID' => 1, 'CatLink' => './PostList.pl?cat=General',
'CatName' => 'General' }, { 'CatID' => 2, 'CatLink' => './PostList.pl?cat=DevOps', 'CatName' => 'DevOps' },
and so on
how do I for example print out the value for example DevOps in the second structure in a perl script. I can do it in a tt template just not perl
2
Answers
If a variable contains a reference, you need to dereference it to access the referenced thing.
$VAR1 is a hash reference, we can dereference it using the arrow.
The value associated with "categories" is a reference to an array reference, so we need to dereference it as a scalar to get an array reference
then we can use the arrow again to get into the array.
BTW, if the
$sth->finish();
is placed after areturn
, it will never be executed.You used
fetchall_arrayref
, and what you got is what that method does. There are other methods, such asfetchall_hashref
and variousselect*
methods that let you shape what the data structure will look like. It looks like you want one of them that returns the row as a hash.