I am somewhat new to Perl, and this bug has puzzled me for a couple of days. I’ve had difficulty finding anything on Google for a problem this specific. I will try to present the “clues” as clearly as possible. I am using Perl v5.16.1. The relevant lines in my code are these:
my %result = ();
...
$result{'TABLENAME'} = $tableName;
...
for my $i (1..$numberOfColumns) {
$result{$columnNames[$i-1]} = $columnValues[$i-1];
}
In my test, $numberOfColumns is 7. The problem is that the for-loop does not create the key-value pairs as I expect. I will explain. I’ve tried debugging using Perl’s debugger with perl -d. The debugger output below shows things going fine until the last line.
DB<2> c 219
testcode::testsub(modules/testcode.pm:219):
219: $result{'TABLENAME'} = $tableName;
DB<3> c 239
testcode::testsub(modules/testcode.pm:239):
239: for my $i (1..$numberOfColumns) {
DB<4> p %result
TABLENAMEmyowntableitis
DB<5> p $result{TABLENAME}
myowntableitis
DB<6> s
testcode::testsub(modules/testcode.pm:240):
240: $result{$columnNames[$i-1]} = $columnValues[$i-1];
DB<6> p $i
1
DB<7> p $columnNames[0]
id
DB<8> p $columnValues[0]
1
DB<9> s
testcode::testsub(modules/testcode.pm:240):
240: $result{$columnNames[$i-1]} = $columnValues[$i-1];
DB<9> p $i
2
DB<10> p %result
TABLENAMEmyowntableitisid
1
DB<11> p $result{TABLENAME}
myowntableitis
DB<12> p $result{id}
DB<13>
I expected the last p $result{id} to return 1 instead of nothing. Does anyone have an idea what could be happening here?
If we look at
DB<10>, we see that the1is printed on the next line:This means that
$result{"id\n"} eq "1", and you are using an undefined key.A style note:
foreaching over two arrays to build a hash is possible, of course. But then again, Perl has slices, which makes life much easier (unless you are processing incredible large amounts of data)(assuming
@columnNames <= @columnValues)