Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Journal of nicholas (3034)

Sunday February 05, 2006
07:26 PM

Duff's device in Perl 5

[ #28586 ]

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...

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.