in reply to Re: Function reference undef when extract from hash?
in thread Function reference undef when extract from hash?

I used strict and warning.

And the call of the build_sth('set_to_flag') in another function which is called in the main per script:

(continue with previous code) sub somecall{ build_sth('set_to_flag') } somecall();
I have checked the previous version where I got trapped. I get the code fail when I move the hash outside of function:
my %Op = ( set_to_flag => \&write_flag, set_tree => \&write_sets, default => \&do_nothing ); sub build_sth { my ($op_code) = @_; my $op_exec = $Op{$op_code} ; if( defined $op_exec ){ $op_exec->(); }else{ print "Oops\n"; } }
why the code fail in this case?

Replies are listed 'Best First'.
Re^3: Function reference undef when extract from hash?
by ikegami (Patriarch) on Mar 04, 2008 at 00:55 UTC

    why the code fail in this case?

    The only possibly reason is if build_sth('set_to_flag') is called before my %Op = ( ... ); is executed.

    Otherwise, it doesn't fail.

    sub write_flag { print "write_flag\n"; } sub set_tree { print "set_tree\n"; } sub do_nothing { print "do_nothing\n"; } ... code you provided ... build_sth('set_to_flag'); # Prints write_flag