sarf13:
It looks like a typical "fencepost" error. If your file has 10 columns, then $cnt will be set to 10. So far, so good. Then you're starting your columns at 0 for the worksheet. Again, that's good.
But then your while loop tries to write all the way up to column 10 in the spreadsheet, which is the eleventh column in your array. Since it has only 10 columns, it's grabbing an uninitialized value and feeding it to the module.
You can avoid errors like that by using a different idiom--Let perl detect the end of the array. You just do your part of the operation, namely writing the values to the spreadsheet and increment the column:
#method 1: Perl will iterate over the array, so we just
#increment the counter at each write
$worksheet->write_string($row, $col++, $_) for @Fld;
#method 2: If you need a loop (so you can do something
#else in the code, too), you can do it like:
for my $item (@Fld) {
$worksheet->write_string($row, $col++, $item);
# do something else here...
}
#method 3: If you don't mind destroying the @Fld array,
#you could also:
while (my $item = shift @Fld) {
$worksheet->write_string($row, $col++, $item);
# do something else here...
}
There are a few other ways to approach it, too.
Note: I've also seen "off by one error", "edge case" and "boundary error" used in place of "fencepost error". I like the term fencepost error because it contains a nice visual: You need 11 fenceposts for 10 sections of fence. It's pretty easy to forget the fencepost that holds up the "other" end of the span when you're counting on each post to be the beginning of one and the end of the previous section.
...roboticus
When your only tool is a hammer, all problems look like your thumb. |