jqcoffey has asked for the wisdom of the Perl Monks concerning the following question:
I have an optimization/minimum typing question. I wonder what the best and/or shortest method is for assigning default values to variables. For example, a typical subroutine call for me looks like:
use vars qw($VAR2); # global defaults and whatnot $VAR2 = 'thingamabob'; sub routine { my $input_ref = {@_}; my $var1 = $input_ref->{var1} || ''; my $var2 = $input_ref->{var2} || $VAR2; ...etc... }
This seems to work fairly well for me, however, it doesn't allow me create subroutine boolean flag called "do_this" that defaults to true, but the user can explicitly set false, eg:
sub routine { my $input_ref = {@_}; my $do_this = $input_ref->{do_this} || 1; }
If the user calles routine( do_this => 0 ), do_this will, obviously still be true. Now, I know how to code around this with:
my $do_this = 0; if ($input_ref->{do_this} eq '0') { $do_this = 0 } else { $do_this = 1 };
But that seems a little long winded. I was wondering if the Monks had any input (ha!) on this, or if my whole default assignment strategy is misguided.
Thanks,
Justin
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Best method of assigning "default" values?
by Transient (Hermit) on Jun 28, 2005 at 15:46 UTC | |
by davidrw (Prior) on Jun 28, 2005 at 15:50 UTC | |
|
Re: Best method of assigning "default" values?
by Mutant (Priest) on Jun 28, 2005 at 16:41 UTC | |
by mrborisguy (Hermit) on Jun 29, 2005 at 03:10 UTC | |
|
Re: Best method of assigning "default" values?
by ikegami (Patriarch) on Jun 28, 2005 at 15:56 UTC | |
|
Use Params::Validate or a similar module
by rrwo (Friar) on Jun 29, 2005 at 10:16 UTC | |
|
Re: Best method of assigning "default" values?
by Zaxo (Archbishop) on Jun 29, 2005 at 03:20 UTC |