[OT] Perl woes

Jonathan McKeown jonathan+londonpm at hst.org.za
Wed Jan 28 13:13:37 GMT 2009


On Wednesday 28 January 2009 14:30:20 Jonathan Kimmitt wrote:

> However, what about this one:
>
> for (my $i==0; $i<($tbl_width - 1); $i++) { .... }
>
> Is anybody seriously arguing this could possibly do anything useful. Yet
> it is not trapped out as an error unless you add the obscure syntax:
>
> use warnings FATAL => 'all';

I think you've got two mistakes here. If you wanted to go round the loop 
$tbl_width times starting from 0, you needed either

$i <= ($tbl_width - 1)

or

$i < $tbl_width

In Perl, most people would write

for my $i (0 .. $tbl_width - 1) { ... }

It's much easier to read than an old-fashioned C-style for-loop, and it's much 
harder to make the off-by-one error I think you made above.

Also, if you have by any chance something similar to $column = $table[$i] 
inside the for-loop, you should probably be writing

for my $column (@table) { ... }

instead.

Perl is immensely frustrating if you work against it and a real pleasure once 
you start to work with it.

Jonathan


More information about the london.pm mailing list