in reply to Blessables -- What Can You Make Into Objects?

This was a cool article. Dont know how useful, but very interesting.
I am sure I will find a use for it somewhere.

I tried to play with blessing RegEx's and ran into trouble.
You mention that you might be able to bless a s{}{}, but I
couldn't figure it out.

I wanted an object that would do "s/^\s+|\s+$/g" for me.
It would not compile if i did somethine like
$self = s{^\s+|\s+$}{}; so I ended up using qr{} instead,
putting the s/// in the member function:
package Cleaner; sub new { my $class = shift; $class = ref($class) || $class; my $self = qr{^\s+|\s+$}; return bless($self, $class); } sub clean { $_[1] =~ s/$_[0]//g; } package main; $c = new Cleaner; $foo = "\t\tFOO\t\t"; $c->clean($foo); print $foo, "\n";
So this works, but I dont know it is the most optimized
routine. I did some benchmarks:
package main; $c = new Cleaner; $foo = "\t\tFOO\t\t"; use Benchmark; timethese(1000000, { 'blessed' => sub { my $bar = $foo; $c->clean($bar) }, 'normal' => sub { my $bar = $foo; $bar =~ s/^\s+|\s$//g }, });
And got these results:
Benchmark: timing 1000000 iterations of blessed, normal... blessed: 43 wallclock secs (36.50 usr + 0.14 sys = 36.64 CPU) normal: 28 wallclock secs (24.19 usr + 0.08 sys = 24.27 CPU)
I guess the difference is just the function call, but thought maybe there is a faster way. Any Ideas?

Replies are listed 'Best First'.
RE: RE: Blessables -- What Can You Make Into Objects?
by chromatic (Archbishop) on Apr 21, 2000 at 08:40 UTC
    Looks like I'm wrong about being able to bless a s{}{} statement. That would be truly convenient. I'll change that in the tutorial.

    In your benchmarking, lots of the time *is* taken up by the function call. Here's what I ran to prove that. (This has to be done in the Cleaner package, for obvious reasons.):

    timethese(1000000, { 'blessed' => sub { my $bar = $foo; $c->clean($foo); }, 'normal' => sub { my $bar = $foo; $bar =~ s/^\s+|\s$//g; }, 'super' => sub { my $bar = $foo; $bar =~ s/$c//g; }, });
    There's not nearly the performance penalty involved:
    Benchmark: timing 1000000 iterations of blessed, normal, super... blessed: 10 wallclock secs ( 9.83 usr + 0.00 sys = 9.83 CPU) normal: 4 wallclock secs ( 5.42 usr + 0.00 sys = 5.42 CPU) super: 7 wallclock secs ( 6.71 usr + 0.00 sys = 6.71 CPU)
    I suspect that if the regex were more complicated (and $foo were much longer), the difference wouldn't be quite as intense.