Perl: cmpthese text vs anonymous sub problems with parameters passed -
if read cmpthese
in perl benchmark module's documentation, states cmpthese
or timethese
can used code in either text or subroutine references. documentation seems imply these forms interchangeable:
# use perl code in strings... timethese($count, { 'name1' => '...code1...', 'name2' => '...code2...', }); # ... or use subroutine references. timethese($count, { 'name1' => sub { ...code1... }, 'name2' => sub { ...code2... }, });
i having difficulties passed parameters string form versus subroutine references form cmpthese
. either values in @array
not passed or have run-time error.
i have following code:
#!/usr/bin/perl use strict; use warnings; use benchmark qw(:all); @array = qw( first second third ); sub target { $str = $_[0]; print "str=$str\n"; } sub control { print "control: array[0]=$array[0]\n"; } $sub_ref=\⌖ $control_ref=\&control; print "\n\n\n"; # error: array not passed... cmpthese(1, { 'target text' => 'target(@array)', 'control 1' => 'control()', }); # ok... cmpthese(1, { 'sub code ref' => sub { target(@array) }, 'control 2' => sub { control() }, }); # ok too... cmpthese(1, { 'target sub' => sub { $sub_ref->(@array) }, 'control 3' => sub { $control_ref->() }, }); # fixed paramenters work: cmpthese(1, { 'target text fixed' => 'target("one", "two", "three")', 'control 4' => 'control()', }); # run time error... cmpthese(1, { 'text code ref' => '$sub_ref->(@array)', 'control 5' => '$control_ref->()', });
all forms have work correctly eval
think may issue benchmark? have used google foo try , find documented difference between 2 forms cannot.
does know reason simple examples above not seem work expected? comments in code indicate problems having on os x, perl 5.10.0.
i haven't looked in detail @ this, guess when benchmark
evals strings code, lexical variable @array
not in scope. things work if made @array
our
variable.
but in general, find easier use code refs.
Comments
Post a Comment