1

I am trying access the data from the database and copy the data to an array. This is my code,

$sth = $dbh->prepare("SELECT * FROM abcd WHERE id=100 "); 
$sth->execute;
$N=$sth->rows;
print "$N\n"; 
while (my @row_val = $sth->fetchrow_array()){
  my ($uniqid, $time, $current, $id ) = @row_val;
  $y[k]=$current;
  $k++;
}
for ($k=0;$k<$N;$k++) {
  print "$y[k]\t";
}

But it displays the same value for all $y[k]. How to copy the data from database to an array in perl?

4

2 回答 2

6

You are using a bareword here:

$y[k]=$current;
#  ^--- here, the "k" is a bareword

If you use warnings this will give a warning

Unquoted string "k" may clash with future reserved word at foo.pl line 10.
Argument "k" isn't numeric in array element at foo.pl line 10.

And the "k" will be interpreted as a string, will be converted to a number, which will be zero 0, so all your data is stored in $y[0].

This is why it is a very bad idea to not turn warnings on.

What you probably want instead is to push the new values onto the array:

push @y, $current;

This is, IMO, preferable to using an index, since it does all that work for you. Usually, you only want to specifically get involved with array indexes if the indexes themselves are of value for you, such as when comparing array elements.

This also means that your subsequent for loop

for ($k=0;$k<$N;$k++) {
  print "$y[k]\t";
}

Is better written

for (@y) {
    print "$_\t";
}

Although this is better written with join:

print join "\t", @y;

As a final note, you should always use

use strict;
use warnings;

It takes a small amount of learning to overcome the additional noise when using these pragmas, but it is well worth it in terms of learning and reducing your time spent debugging. I usually say that not using these pragmas is like covering up the low oil warning lamp in your car: Not knowing about the errors does not solve them.

于 2013-10-09T10:23:19.373 回答
3

This behaviour is because you are putting everything to index "k" - not any number just "k",
it is only a coincidence that its working at all :) - the "same value" is the last value - isnt it ? :)

SOLUTION:

1) variables are written with $ - keep that in mind when accessing $yourArray[$variableWithIndex]

2) $y[k]=$current; # wrong! you are trying to access "k" index correct: $y[$k]=$current;

Didnt tested it - but this should work:

$sth = $dbh->prepare("SELECT * FROM abcd WHERE id=100 "); 
$sth->execute;
$N=$sth->rows;
print "$N\n"; 
$k=0; # init first!
while (my @row_val = $sth->fetchrow_array()){
  my ($uniqid, $time, $current, $id ) = @row_val;
  $y[$k]=$current; # dont forget the $
  $k++;
}
for ($k=0;$k<$N;$k++) {
  print "$y[$k]\t"; # dont forget the $
}
于 2013-10-09T10:23:21.037 回答