Akio Yanagawa
Akio Yanagawa

Reputation: 323

How to use fetchrow_arrayref correctly in perl script?

I got stuck in the usage of 'fetchrow_arrayref' in Perl script. Can anyone point out where I'm going wrong in the script? I'd appreciate whatever you could inform me. Thank you.

The problems I'm facing are:

(1) print $id; <-this doesn't print the content of $id.

(2) print "$list[1]"; <-this prints ARRAY(0x8da6978) instead of the actual content.

(3) reverse(@list); <-this doesn't reverse the contents of @list.

(4) print "@{$_} \n"; <- "\n" doesn't work. Also why do we need @{}?

(5) print "\n"; <-this doesn't work as well.

(6) print "@list"; <-this prints ARRAY(0x8da6978).

(7) print Dumper(@inverse); <-prints fine, but the contents of the array is not reversed.

#!/usr/bin/perl

use strict;
use warnings;
use DBI;
use Data::Dumper;

....

my $dbh = DBI->connect($dbname, $dbuser, $dbpassword) || die "Error $DBI::errstr";
my $sth = $dbh->prepare("SELECT * FROM name WHERE id = 11");
$sth->execute;

my @list = ();

while(my $element = $sth->fetchrow_arrayref){

    push(@list, $element);

}


$sth->finish;
$dbh->disconnect;

my ($id, $name, $email, $telephone) = @list;

print "Content-Type: text/html; charset=UTF-8\n\n";

print $id;                                           (problem 1)

print "$list[1]";                                    (problem 2)

my @inverse = reverse(@list);                        (problem 3)

foreach (@inverse){

    print "@{$_} \n";                                (problem 4)

}

print "\n";                                          (problem 5)

print "@list";                                       (problem 6)

print Dumper(@inverse);                              (problem 7)

exit;

Upvotes: 2

Views: 7646

Answers (2)

Tripti Gupta
Tripti Gupta

Reputation: 11

$sth->fetchrow_arrayref will return the arrayref and you push that on @list. Now the @list array contain the arrayref on every index and the reference will the same. Therefore, you should push the value of array in @list like: push(@list, @$element);

Upvotes: 1

Quentin
Quentin

Reputation: 944556

Each item in your list will be a reference to an array containing the data for one row of your database table.

This:

my ($id, $name, $email, $telephone) = @list;

appears to be trying to process one row of the table.

You need to do that for each member of @list and not @list itself.

for my $row (@list) {
    my ($id, $name, $email, $telephone) = @$row;
    print $id;
}

Upvotes: 2

Related Questions