Hi, Todd (and Wiggins!), :) On Wed, 13 Nov 2002, todd shifflett wrote:
> I am trying to use a code reference from within a function to > recursively call a given separate function... > #--- LIKE THIS --vv > sub hello { > my $name = shift; > return "Hello, $name!\n"; > } > > sub foo { > my($f, @args) = @_; > return &$f(@args); > } > > print foo(\&hello, "world"); > #---^^ > the above works. Now I would like to be able to pass in a > subroutine from a declared object. > #---- This does not work --vv > use Math::FFT; > > my @nums = qw(3 4 5 7 10 8 7 9); > my $fft = new Math::FFT(\@nums); > > # this is fine > my $stdev = $fft->stdev(\@nums); > > # this is not... ERROR: Undefined subroutine &main::fft->stdev called > at ... > print foo(\&{'fft->stdev'},\@nums); > #---^^ > So how do I pass in the subroutine for a given object into my > function to be called later? >From _The Perl Cookbook_, Recipe 11.8: "When you ask for a reference to a method, you're asking for more than just a raw function pointer. You also need to record which object the method needs to be called upon as the object contains the data the method will work with. The best way to do this is using a closure. Assuming $obj is lexically scoped, you can say: $mref = sub { $obj->method( @_ ) }; # [and then] later... $mref->( "args", "go", "here" ); " Make sense? Using this strategy, I rewrote your little test to look like: #!/usr/bin/perl use strict; use warnings; use Math::FFT; my @nums = qw(3 4 5 7 10 8 7 9); my $fft = new Math::FFT( \@nums ); my $stdev = sub { $fft->stdev( @_ ) }; print foo($stdev, \@nums); sub hello { my $name = shift; return "Hello, $name!\n"; } sub foo { my $f = shift; return $f->( @_ ); } (Notice the rewrite of the actual method call in 'foo' - the "&$f" syntax is deprecated, I believe.) After running this, I got: 2.44584195260913 which I assume is correct. ;) Hope that helps! The Cookbook is a great book... ---Jason -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]