At 2004-11-02T11:26:32+1300, Alasdair Tennant wrote:

> OK, OK!  It's a free-for-all!  I had been holding back, BUT Tcl must
> have the neatest function for stepping through lists:-

>       foreach {a b} {1 2 3 4 5 6} { add your code here, using $a and $b }

That's nice and simple.  Just for the sake of it, here's some Perl stuff.



# A fairly simple way (C-like):

@ls = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
while ($i <= $#ls) {
        $a = $ls[$i++];
        $b = $ls[$i++];
        print "$a,$b\n";
}



# If you don't mind modifying the list:

@ls = qw(1 2 3 4 5 6);
while(($a, $b) = splice(@ls, 0, 2)) {
        print "$a,$b\n";
}



# If you are bored and want to be fancy, use closures:

sub pairList (\@) {
        $i = 0;
        @a = @{$_[0]};
        sub {
                $i >= @a ? () : ($a[$i++], $a[$i++]);
        }
}

@array = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
$ls = pairList(@array);

while (($a, $b) = $ls->()) {
        print "$a,$b\n";
}



And, being Perl, there are even more ways to achieve the same thing.

> Now somebody out there will do it in 5 obscure characters using Perl!

My implementation using closures is a little obscure, but that's because
I wrote it that way deliberately.  It's easy to write obscure code in
any language.  If you can be terse at the same time, you might as well.
;-)

Cheers,
-mjg
-- 
Matthew Gregan                     |/
                                  /|                [EMAIL PROTECTED]

Reply via email to