[Melbourne-pm] How to create data structures with 'default values'

Timothy S. Nelson wayland at wayland.id.au
Mon Nov 17 19:08:39 PST 2008

On Mon, 17 Nov 2008, Alec Clews wrote:

> G'Day Perl Bunnies,
> I have created a hash structure with a set of environment specific keys
> and values.
> * There is a different hash for each of the environments.
> * Many of the values are the same (default) across all the
> environments. 
> What is the easy way of setting up the defaults once and then have each
> environment overwrite the default values with specific settings?
> Currently I have a hash of defaults. However it's a pain to define each
> specific value or assign the default value for every single key in every
> single environment.

 	Is this the sort of thing you were thinking of?


use     Data::Dumper;

%defaults = (
         key1 => "value1",
         key2 => "value2",
         key3 => "value3",

$specifics = {
         key2 => "value4",

%keyhash = map { $_ => 1 } keys %defaults, keys %$specifics;

%actual = map {
 	$_ => exists($specifics->{$_}) ? $specifics->{$_} : $defaults{$_}
} keys %keyhash;

print Dumper \%keyhash, \%actual;

 	I've made %defaults a hash and $specifics a hash reference, but that 
was just to demonstrate more things.

| Name: Tim Nelson                 | Because the Creator is,        |
| E-mail: wayland at wayland.id.au    | I am                           |

Version 3.12
GCS d+++ s+: a- C++$ U+++$ P+++$ L+++ E- W+ N+ w--- V- 
PE(+) Y+>++ PGP->+++ R(+) !tv b++ DI++++ D G+ e++>++++ h! y-

More information about the Melbourne-pm mailing list