Here is the manner in which I would approach this based on the (what appears to be) non OO Perl you posted. The assignment of the values could be shorten based on some of the other posts. In reviewing the other posts it dawned on me that adding anonymous hash refs might make this more confusing so apology in advance if it does.
use Data::Dumper;
use strict;
# here is our default values for various
# parameters. We set this up so we have
# a central spot to set defaults, or
# you could say a poor mans conf routine.
our $defaults = {
call_it => {
incoming => 'text',
argument => 'value',
parameter => 'hello'
},
call_this => {
incoming => 'text',
argument => 'value',
parameter => 'hello'
},
};
# call our sub passing an anonymous hashref
call_it( { incoming => 'html' } );
sub call_it {
# pull off our first value which is our hashref
my $args = shift;
# loop through what should be our defaults
# based on our defaults hashref above
foreach (keys %{$defaults->{call_it}}) {
$args->{$_} ||=
$defaults->{call_it}{$_}
}
# print out our new args
# complete with our defaults and our
# passed parameter preserved.
print Dumper($args);
}
# below we move the assignment into another sub
# this helps if we are going to be doing this often
# another reason to do this is so that if you
# make changes to how you merge the parameters
# with the defaults you only have to edit this
# one sub vs. replacing every copy and paste
# of it.
# here is our assignment function
sub assign_defaults {
my ($hashref,$sub) = @_;
foreach (keys %{$defaults->{$sub}}) {
$hashref->{$_} ||=
$defaults->{$sub}{$_}
}
return $hashref;
}
# call our sub
call_this( { parameter => 'good bye' } );
# this sub uses the new assign_defaults
# as would any other sub that needs it
sub call_this {
my $args = shift;
$args = assign_defaults($args,'call_this');
print Dumper($args);
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|