[Pdx-pm] oh, gross (object method in regex)

Randall Hansen randall at sonofhans.net
Sun Mar 12 16:20:45 PST 2006


On Mar 12, 2006, at 3:46 PM, Eric Wilhelm wrote:

> Is this prettier?
>
>   grep /@{[ $object->method ]}/ => @stuff;

heh ... a little.  it's more magical, anyway, and that's something.

for chromatic & david (thank you all, btw):  the method returns a  
scaler.  david's method of assigning to a temporary variable works,  
and is what i've done before, but seemed ugly and wasteful because i  
only used it once.

so the reference/dereference syntax avoids the temporary variable, is  
faster[1], and explicit enough so that people who understand the rest  
of my code will get it.

thanks for thinking about it with me.

r

----
1. ref/deref is a little faster.  eric's magic (i.e. "the secret  
operator") is very slow.

Benchmark: timing 100000 iterations of deref, eric, temp...
     deref:  3 wallclock secs ( 1.45 usr +  0.01 sys =  1.46 CPU) @  
68493.15/s (n=100000)
     eric: 14 wallclock secs ( 9.79 usr +  0.11 sys =  9.90 CPU) @  
10101.01/s (n=100000)
     temp:  4 wallclock secs ( 2.18 usr +  0.02 sys =  2.20 CPU) @  
45454.55/s (n=100000)


#!/usr/bin/perl
use strict;
use warnings;

package Foo;
     sub new { return bless {}, shift }
     sub foo { 'foo' }

package main;
     use Data::Dumper;
     use Benchmark qw/ :all /;

     my $count = 100_000;

     timethese( $count, {
         'temp'    => \&temp,
         'deref'   => \&deref,
         'eric'    => \&eric,
     });

     sub temp {
         my $Foo = Foo->new;
         my @search = qw/ baz bar foo bang /;
         return grep /${ \$Foo->foo }/ => @search;
     }

     sub deref {
         my $Foo = Foo->new;
         my @search = qw/ baz bar foo bang /;
         my $foo = $Foo->foo;
         return grep /$foo/ => @search;
     }

     sub eric {
         my $Foo = Foo->new;
         my @search = qw/ baz bar foo bang /;
         return grep /@{[ \$Foo->foo ]}/ => @search;
     }




More information about the Pdx-pm-list mailing list