« Pan Fried Gnocchi | Main | The Thinker’s Thesaurus »

Loop without Loop

Today’s installment of execrable Perl inspired by inexperienced coders asking koan-esque questions “how do I loop over something, but without looping over it?” Actual user question in this case turned out to be $ref->foo->foo->… iteration, which would require a slightly different recursive call. But this let me fiddle with &… prototypes to good effect.

#!/usr/bin/perl -w # Abuse recursion and so forth to # "loop without looping". use strict; # So don't need () and can specify # a sub-less sub. sub loop (&$;$); my @list = qw(a b c d); # No way known to specify @list, then # use reference in subsequent calls loop { print } \@list; sub loop (&$;$) { # Use @_ directly instead of named # variables as prototype disallows # repassing code ref (insists # on a block...) local $_ = $_[1]->[ $_[2]++ ]; eval { &{ $_[0] } }; if ($@) { # ed(1) style error messages :) die "!\n"; } $_[2] > $#{ $_[1] } || &loop; }