legLess has asked for the wisdom of the Perl Monks concerning the following question:
The "exists" test on the error line isn't the first thing I tried, just the most recent, and it's nicely illustrative of what I want to do. I understand why the error's happening, but I can't think of a way to check for that subref without dying (eval, perhaps, but I'm hoping there's another way). I also know I could standardize the hash structure as follows (with attendent changes in the rest of the code, of course):my %runmodes = ( config_item => 'regular', action1 => sub{ print "action = 1" }, action2 => sub{ print "action = 2" }, action3 => { config_item => 'special', subroutine => sub{ print "action = 3" }, }, ); sub get_config_item { my( $runmodes, $action ) = @_; my $config_item = $runmodes->{ config_item }; if( exists $runmodes->{ $action }{ subroutine } ) { # error line &{ $runmodes->{ $action }{ subroutine }}; $config_item = $runmodes->{ $action }{ config_item }; } else { &{ $runmodes->{ $action }} } return $config_item; } print ", ", get_config_item( \%runmodes, "action3" ), "\n"; print ", ", get_config_item( \%runmodes, "action1" ), "\n"; # OUTPUT # # action = 3, special # Not a HASH reference at str.pl line 22.
But two things bug me about that solution. First, those extra "subroutine"s sitting there, redundant, look ugly. Second, regardless of how I solve this particular problem, I still don't know if there's a way to do what I'm trying. Thanks muchly for any assistance.my %runmodes = ( config_item => 'regular', action1 => { subroutine => sub{ print "action = 1" }}, action2 => { subroutine => sub{ print "action = 2" }}, action3 => { config_item => 'special', subroutine => sub{ print "action = 3" }}, }, );
|
---|
Replies are listed 'Best First'. | |
---|---|
•Re: Testing for existence of subroutine ref?
by merlyn (Sage) on Feb 18, 2003 at 03:38 UTC | |
by feanor_269 (Beadle) on Feb 19, 2003 at 03:10 UTC | |
by djantzen (Priest) on Feb 19, 2003 at 03:43 UTC | |
by ihb (Deacon) on Feb 20, 2003 at 01:25 UTC | |
Re: Testing for existence of subroutine ref?
by djantzen (Priest) on Feb 18, 2003 at 03:43 UTC | |
Re: Testing for existence of subroutine ref?
by bbfu (Curate) on Feb 18, 2003 at 03:38 UTC |