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

Easy one for y'all experts but not for this noob!

Have a simple subr &HTMLFTR to do a series of print stmts and that subr is then called by a series of error routines like $Too_long and $no_name, etc (neither level subr get any arguments from calling mainline, but $no_name etc do call $HTMLHDR with a set of arguments so I've done some of this before but not this situation)

Now I need to test a Y/N switch in &HTMLFTR that was set in mainline to determine if a given print stmt should be done or not...so how do I easily pass the switch downstream to the 2nd level subr $HTMLFTR when I call $cap_err without messing up other subr calls like $no_name that don't need the switch? And all the other calls to $HTMLFTR that don't need it either?

Thanks much! Now heading to bed and hope an answer awaits me in the morning....
  • Comment on Passing switch to 2nd level subroutine?

Replies are listed 'Best First'.
Re: Passing switch to 2nd level subroutine?
by BrimBorium (Friar) on Dec 28, 2010 at 12:08 UTC

    You could use a different design ;-) or pass the switch as last parameter and ignore it if it is undef (kind of optional parameter) or you can use a hashref as parameter and change the behaviour depending on the keys/values. But I personally dislike the last idea and would check for different design.

Re: Passing switch to 2nd level subroutine?
by johngg (Canon) on Dec 28, 2010 at 13:32 UTC

    You could change your subroutine calls slightly to use named arguments by passing a hash rather than a list. (I'm assuming that your mixture of $ and & is a typo and that you are using named subroutines rather than code references.) Something like this code structure might fit the bill:-

    ... my $yes_no = 1; ... if ( $error_cond eq 'too long' ) { too_long(); } elsif ( $error_cond eq 'no name' ) { no_name(); } elsif ( $error_cond eq 'cap err' ) { cap_err(); } else { fallback(); } ... sub too_long { my %args = ( length => $len, type => q{Some type} ); HTMLFTR( %args ); } sub no_name { my %args = ( request => $req, type => q{Another type} ); HTMLFTR( %args ); } sub cap_err { my %args = ( yes_no => $yes_no, type => q{Odd type} ); HTMLFTR( %args ); } sub fallback { ... } sub HTMLFTR { my %args = @_; ... if ( exists $args{ yes_no } ) { print $args{ yes_no } ? "Yes\n" : "No\n"; } ... }

    By using named parameters it no longer matters what order you pass the arguments or whether some or all are present. I hope this idea is helpful.

    Cheers,

    JohnGG

Re: Passing switch to 2nd level subroutine?
by JCHallgren (Sexton) on Dec 29, 2010 at 02:38 UTC
    Thanks to both of you for the answers -- it gave me enough ideas on how to handle the problem -- though I ended up doing it a slightly different way but it works and best, I know what I did!