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

Monks,

I'm used to call functions like this:

my %commands = ( command1 => { description => "Does something", function => sub { my $var = shift; print "var = $var\n"} }, ) my $cmd = 'command1'; $commands{$cmd}{function}($param)

So I thought it could be as easy to quickly change, for development purposes, a function under test by doing:

my $func = \&version1; is($func($param), 0, 'makes sense'); my $func = \&version2; is($func($param), 0, 'does it ?'); sub version1{[some code]} sub version2{[some code]}

But no dice. Syntax error.

So how are 'function pointers' used with scalars ?

Thanks !

Replies are listed 'Best First'.
Re: Quickly changing a function under test in Test::More
by duff (Parson) on Mar 09, 2006 at 13:30 UTC
Re: Quickly changing a function under test in Test::More
by fizbin (Chaplain) on Mar 09, 2006 at 14:52 UTC
    Others have already pointed you at the appropriate references (which you should now go read), but the basic reason is that this:
    $commands{$cmd}{function}($param)
    is really (for some values of "really") this:
    $commands{$cmd}->{function}->($param)
    It's just that perl allows you to omit the -> bit when you have two adjacent sets of parentheses, braces, or brackets. This phenomenon can be seen be using Deparse:
    $ perl -MO=Deparse -e 'print $a{funclist}[0](4);' print $a{'funclist'}[0](4); -e syntax OK $ perl -MO=Deparse -e 'print $a{funclist}->[0]->(4);' print $a{'funclist'}[0](4); -e syntax OK
    See how the output code is the identical? That means that the input code was parsed identically. (or that you've stumbled onto one of the obscure bugs in Deparse)

    However, in you test code you don't have two adjacent sets of delimiters, so you aren't allowed to omit the -> bit. Use $func->($param), as other posters have already said.

    --
    @/=map{[/./g]}qw/.h_nJ Xapou cets krht ele_ r_ra/; map{y/X_/\n /;print}map{pop@$_}@/for@/
Re: Quickly changing a function under test in Test::More
by gube (Parson) on Mar 09, 2006 at 14:18 UTC

    Hi try this,

    #!/usr/local/bin/perl use strict; use warnings; use Data::Dumper; my %commands = ( 'command1' => { 'description' => "Does something", 'function' => sub { my $var = shift; return "var = $var\n" } } ); my $cmd = 'command1'; print $commands{$cmd}{'function'}->("hello");

    It's reference part, to learn more about reference, go through perlref link, above given by duff.