[OT] Perl woes

muppet scott at asofyet.org
Fri Jan 30 05:05:58 GMT 2009


On Jan 28, 2009, at 9:58 AM, Jonathan McKeown wrote:

> On Wednesday 28 January 2009 15:24:43 Jonathan Stowe wrote:
>> 2009/1/28 Jonathan McKeown <jonathan+londonpm at hst.org.za>:
>>> 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 suspect that the actual problem is the use of the comparison rather
>> than assignment in the first clause of the C style for.
>
> Yes, I'd spotted that: that's the first mistake. The second is what  
> appears to
> be an off-by-one in the termination condition (usually if you  
> mention 0 and
> $tbl_width-1 in the same expression it's because you want to start  
> at 0 and
> go round $tbl_width times, which the original code doesn't achieve).

It certainly smells like an off-by-one, but might not be.  Depends  
completely on what's in the loop body.  Maybe he's doing this:

    my $string = '';
    my $table_width = $#table_val;
    for (my $i = 0 ; $i < ($table_width - 1) ; i++) {
       $string .= $table_val[$i] . ", ";
    }
    $string .= $table_val[$#table_val];

(in which case, we say, "i'd like you to meet my friend join()"...)   
or, more realistically:

    for (my $i = 0 ; $i < ($table_width - 1) ; i++) {
       push @deltas, $table[$i + 1] - $table[$i];
    }

which can still be written as

    @deltas = map { $table[$_] - $table[$_-1] } 1..$#table;

for those of us with matlab in our brains, or

     for my $i (1..$#table) {
         push @deltas, $table[$i] - $table[$i - 1];
     }

for those who can't abide vectors and map.


An interesting thing is that since $i was a lexical in the loop, and  
incremented in the loop, then perl will actually try to do the right  
thing -- applying ++ to undef results in 1.


--
Overheard during a game of Lego Star Wars II:
Zella: I can't do it!
Yvonne: You have to do it!
Zella: I'm trying!
Yvonne: There is no try!





More information about the london.pm mailing list