Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Function reference undef when extract from hash?

by reneeb (Chaplain)
on Mar 03, 2008 at 11:09 UTC ( #671635=note: print w/ replies, xml ) Need Help??


in reply to Function reference undef when extract from hash?

Do you use use strict and use warnings? Where do you call build_sth('set_to_flag')?

This works:

#!/usr/bin/perl use strict; use warnings; build_sth( 'set_to_flag' ); sub write_flag{ print "Success for flag.\n"; } sub write_sets{print "Success for Set.\n"; } sub do_nothing{print "Exit Here\n";} sub build_sth{ my ($op_code) = @_; my %Op = ( set_to_flag => \&write_flag, set_tree => \&write_sets, default => \&do_nothing ); my $op_exec = $Op{$op_code} ; if( defined $op_exec ){ $op_exec->(); }else{ print "Oops\n"; } }


Comment on Re: Function reference undef when extract from hash?
Download Code
Re^2: Function reference undef when extract from hash?
by Anonymous Monk on Mar 03, 2008 at 18:25 UTC

    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?

      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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://671635]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2015-07-04 07:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (58 votes), past polls