http://qs321.pair.com?node_id=50132


in reply to What Happened...(perils of porting from c)

Here is a native Perlish thing that basically does what I think you really want. Note how much shorter this is than the C version.
use strict; nested_for( sub {print "@_\n";}, [1..2], ['a'..'c'], ['A'..'D'] ); sub nested_for { ret_iter(@_)->(); } sub ret_iter { my $fn = shift; my $range = shift; my $sub = sub {$fn->($_, @_) for @$range}; return @_ ? ret_iter($sub, @_) : $sub; }
Also note the lack of pointer arithmetic to mess up on. :-)

Replies are listed 'Best First'.
Re: Re (tilly) 1 (perl): What Happened...(perils of porting from c)
by Madams (Pilgrim) on Jan 06, 2001 at 05:20 UTC
    Oh Wow!

    I bow to tilly!

    I am going to REALLY study this: it works! correctly! it's one-third the size! it looks tricky but not f**** insane! and NO POINTER ARITHMETIC!!!!

    This is the sort of answer that shows that i'm a tyro at perl AND why! I'm obviously still stuck in some sort of tunnel vision caused by programming in c/c++.

    To me this is a great Zen Koan to meditate on!

    Thanks tilly, and everyone who responded to this query!

    ---madams :) x $POSIX::LDBL_MAX
Re: ancient masterpiece
by Roy Johnson (Monsignor) on Jun 02, 2005 at 22:27 UTC
    That was beautiful. I'm writing primarily so more people can see it. I also did a little rewrite that isn't an improvement, per se, but is AWTDI and may help people understand what's going on. (Iterating instead of recursing.)
    sub ret_iter { my $sub = shift; while (my $range = pop) { my $inner = $sub; $sub = sub { $inner->(@_, $_) for @$range }; } return $sub; }
    I made it so it changes elements on the right fastest, like a counter.

    Caution: Contents may have been coded under pressure.