There has already been debate here about whether Perl 6 should permit Duff's device
Too late, I fear. It already seems to work quite nicely in Perl 5:
#!/usr/bin/perl -w use Test::More 'no_plan'; sub copy_duff { my ($count, $to, $from) = @_; return if $count <= 0; my $i = 0; my $j = 0; my $loops = int(($count+7)/8); goto "l" . ($count%8); do {l0: $to->[$i++] = $from->[$j++]; l7: $to->[$i++] = $from->[$j++]; l6: $to->[$i++] = $from->[$j++]; l5: $to->[$i++] = $from->[$j++]; l4: $to->[$i++] = $from->[$j++]; l3: $to->[$i++] = $from->[$j++]; l2: $to->[$i++] = $from->[$j++]; l1: $to->[$i++] = $from->[$j++]; } while(--$loops>0); } foreach my $count (0..17) { my @from = 0..$count; foreach my $copy (0..$count) { my @to; copy_duff($copy, \@to, \@from); # And test is_deeply(\@to, [0..$copy-1], "count = $count, copy = $copy"); } }
Although quite what it's useful for I don't know. I have a horrible suspicion that like C, unrolling the loop may actually be more efficient in Perl too. That is, if you can do better than me and find an operation that actually needs to be in the loop. On the other hand, I suspect that there's scope for the obfuscation writers here...
Abigail claims he first did Duff's Device in Perl way back in 1998 in this PM thread. Also of note is a couple of replies from Larry (aka TimToady).