in reply to Interesting line which I read from Monk's snippets

Greetings jesuashok,

It's a very curious line, and others have explained what it does already; however, it has a couple negatives: It's not easily understood, and it's slower than a more easily understood alternative.

use strict; use warnings; use Benchmark qw(cmpthese); cmpthese( 100000, { 'ahash' => sub { my $pat = {qw(a - b = c ~ d ^)}->{substr($0, 0, 1)}; }, 'tr' => sub { (my $pat = substr($0, 0, 1)) =~ tr/abcd/-=~^/; }, }, );

The above benchmark returns this:

Rate ahash tr ahash 75120/s -- -86% tr 541712/s 621% --

It's a nice trick, but I wouldn't use it anywhere except in an obfu.

gryphon
Whitepages.com Development Manager (WDDC)
code('Perl') || die;

Replies are listed 'Best First'.
Re^2: Interesting line which I read from Monk's snippets
by pKai (Priest) on Jan 31, 2006 at 08:30 UTC

    To deliver the same result (i. e. undef) for not found input values, the tr solution has to be a bit more elaborate.

    Somewhat along the line of

    my $found = (my $pat = substr($0,0,1)) =~ tr/abcd/-=~^/; $pat = $found ? $pat : undef;