mysqlperldbi

Need to iterate a hash returned from a mysql query


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


Solution

  • If a variable contains a reference, you need to dereference it to access the referenced thing.

    my $VAR1 = {
        categories => \[
                          [
                            1,
                            'General',
                            './PostList.pl?cat=General'
                          ],
                          [
                            2,
                            'DevOps',
                            './PostList.pl?cat=DevOps'
                          ]
                      ]  # <- this was missing in your code!
    };
    print ${ $VAR1->{categories} }->[1][1];  # DevOps
    

    $VAR1 is a hash reference, we can dereference it using the arrow.

    $VAR1->{categories}
    

    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

    ${ $VAR1->{categories} }
    

    then we can use the arrow again to get into the array.

    ${ $VAR1->{categories} }->[1]
    

    BTW, if the $sth->finish(); is placed after a return, it will never be executed.