monkfan has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
Why my code below seems to unable to benchmark a method taken from String::Approx?

#!/usr/bin/perl -w use strict; use Data::Dumper; use String::Approx qw\amatch\; use Benchmark 'cmpthese'; #----------Begin Benchmarking-------------- my $str = 'AAAAA'; my @arr = ('AAAAA','ATAAA','ATCGA','ATCAA'); my @my_match = mymatch($str,2,\@arr); print Dumper \@my_match; my @jk_match = amatch($str,['2'],@arr); print Dumper \@jk_match; #It fails here cmpthese (-5,{ me => "mymatch($str,2,\@arr)", jk => "amatch($str,['2'],@arr)",}); #------------------ Subroutine ------------- sub mymatch { my ($pattern, $d, $arr_2match) = @_; my @matches; foreach (@$arr_2match){ my $diff = hd($pattern,$_); #print "$_ --- Diff: $diff\n"; if ($diff <= $d){ push @matches, $_; } } return @matches; } sub hd { #String length is assumed to be equal my ($a,$b) = @_; my $len = length ($a); my $num_match=0; for (my $i=0; $i<$len; $i++) { # assume that the lists are of same length ++$num_match if substr($a, $i, 1) ne substr($b, $i, 1); } return $num_match; }
Such that it gives this result:
[snip others] Can't locate object method "ATCGA" via package "ATCAA" (perhaps you forgot to load "ATCAA"?) at (eval 7) line 1.
Is Benchmark only cater for Perl written subroutine/module? Is there a way to overcome it?
Regards,
Edward

Replies are listed 'Best First'.
Re: Benchmarking String::Approx
by Joost (Canon) on Apr 06, 2005 at 16:11 UTC
Re: Benchmarking String::Approx
by gam3 (Curate) on Apr 06, 2005 at 17:08 UTC
    There seems to be some interaction in the string eval as this code does run.
    cmpthese (-5,{ me => "mymatch('AAAAA',2,['AAAAA','ATAAA', 'ATCGA','ATCAA']);", jk => "amatch('AAAAA',['2'],('AAAAA','ATAAA', 'ATCGA','ATCAA'));" });
    While Joost is wrong (or I misunderstood him) about not being able it give Benchmark a string. His approach is normally the better one.

    Update: The problem is that you are evaling the following strings:

    mymatch(AAAAA,2,@arr)
    amatch(AAAAA,['2'],AAAAA ATAAA ATCGA ATCAA)
    
    -- gam3
    A picture is worth a thousand words, but takes 200K.
Re: Benchmarking String::Approx
by Tanktalus (Canon) on Apr 06, 2005 at 17:06 UTC

    I like to avoid the string version of anything that resolves to eval. You may get better error messages by changing it to:

    cmpthese (-5,{ me => sub { mymatch($str,2,@arr) }, jk => sub { amatch($str,['2'],@arr) }, });
    (The escapes on @arr or lack thereof are confusing me...)