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

Toby Corkindale toby.corkindale at strategicdata.com.au
Mon Nov 17 15:35:03 PST 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 overkill?

package Your::Configuration;
sub colour { 'black' }
sub volume { 11 }
sub new { bless $_[0]; }
1;

package Your::Configuration::Win32;
use parent 'Your::Configuration';
sub colour { 'blue' }
1;

package Your::Configuration::MacOS;
use parent 'Your::Configuration';
sub colour { 'white' }
1;


package main;
use Your::Configuration::MacOS;
# For bonus marks, use a factory class instead.
my $config = Your::Configuration::MacOS->new;
say "Volume is turned up to: " . $config->volume;


As another poster already mentioned - try YAML. It supports defaults and 
overrides, at least in the later versions.

-- 
Strategic Data Pty Ltd
Ph: 03 9340 9000


More information about the Melbourne-pm mailing list