0

My code:

my $sql_query = "select Event_datetime,Event,User from logs";
my $sth = $dbh->prepare($sql_query);
$sth->execute();
$testResults = $sth->fetchall_arrayref();
foreach my $row (@$testResults) {
    ($Event_datetime,$Event,$User) = @$row;
    print $query->h2($ID);
}

I would like to use a for loop to fetch the results of this query(once it is executed) such that each row has a number, i.e. since rows are listed sequentially, I need to access the row by its row number.

i.e. row 1 is 0; row 2 is 1; row 3 is 2 and so on...

for example:

for ($i=0; $i < $noOfRows; $i=$i+1) {
    ($ID,$Event_datetime,$Event,$User) = @$testResults;
    print $query->h3($ID, ' ,', $Event_datetime, ',', $Event, ',', $User );
}

However, this query does not give me any output. How do I access a particular row by its row number ?

1
  • 2
    Add use strict; and use warnings; to the top of your file. You are not showing a reproducible example. Commented Jul 25, 2017 at 3:24

1 Answer 1

0

You can see also Perl How to get the index of last element of array reference?

my $lastRowIdx = $#$testResults;
for (my $i=0 ; $i<=$lastRowIdx ; $i++ ) {
  my $rref = $testResults->[$i];
  print "@$rref\n";
} # endfor;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.