in reply to efficient string translation?

If all you're trying to accomplish is to reduce the effects of an eval in a tight loop, you could cache it.

{ my %pwdrots; sub pwdrot { my $pwd = shift; my $degree = (@_ > 0) ? ((shift) % 94) : 47; if ($degree == 0) { return $pwd; } if (length($str) == 0) { return $pwd; } unless ($pwdrots{$degree}) { my $rangstr = "\\" . sprintf("%03lo",$degree+33) . "-\\176\\041- +\\" . sprintf("%03lo",$degree+32); $pwdrots{$degree} = eval "sub { $_[0] =~ tr[\041-\176][$rangstr] + }" } $pwdrots{$degree}->($pwd); return $pwd; } }

The idea is that you generate an anonymous sub which does the tr, once that is compiled once, you don't need to compile it again (for the same $degree).

Replies are listed 'Best First'.
Re^2: efficient string translation?
by 5mi11er (Deacon) on Jan 27, 2005 at 19:59 UTC
    Ah, good thought. So, by doing this the "compiled" eval is kept in memory and this eval, if called again is much more efficient? Oh, wait! The eval is only done once per degree, the compiled translation subroutine is assigned to the %pwdrots hash, then used as needed.

    Excellent! This makes a file of x strings all using the same transformation a lot more efficient.

    In reality, I'm hoping for a slightly more philisophical discussion of the pro's and con's of the various methods available. Holding some hope for a magical "use this instead of an eval'ed tr//".