Perl gotcha’s–arrays

Working with some existing code to pull data from a MySQL database I ran the following code:


$SQL  = "SELECT id FROM `sensors` ";
$SQL .= "WHERE `storage_table` LIKE '$source_temperature_table' ";

$r = $db->query($SQL);
my $src_sensor_id = $r->getNextRow();
print "The id is $src_sensor_id \n";

No matter which table I ran this on, I always got 1 as the id. So I tried looking at the value of $r using print $r; and the correct ID was showing up. The reason is that perl is different from other languages that I use when it comes to arrays. When I thought I assigned the only value in $r to $src_sensor_id, what I was really doing was assigning the count of the number of rows in $r to $src_sensor_id. When I printed $r, the print statement printed all of the values in the array $r because that’s how print statements handle arrays.

The correct way to assign the array values in $r to variables is to put parentheses around the list of variables in the array. e.g.


my ($src_sensor_id) = $r->getNextRow();

If you have multiple items in the array, separate the variables with commas. e.g.


my ($src_sensor_id, $location, $name) = $r->getNextRow();