incorporating local variables in a global hash in perl

144 views Asked by At

I need to incorporate a generic hash (macro) in multiple user hashes. In actuality these are all specifications written as HoH/HoL in perl.

I would like the 'user' specs to adopt the macro specs with their own modifications. In example below, the variable '$v_Y' needs to have different values in user1 and user2.

What I have below is not exactly code, but an attempt to illustrate the problem. I am unable to have multiple values of $v_Y since macro_spec is already created.

## this is in a package
my $MACRO_SPEC = {
  mkeyX   => "value_X",
  mkeyY   => $v_Y,
};

#this is USER1 package,
$v_Y = "U1_VALUE_X";
# use MACRO_SPEC
my $USER1 = (
  u1key1 => "u1value1",      u1macrokey => $MACRO_SPEC,  # need macro to interpolate 'local' $v_Y 
);

#this is USER2 package,
$v_Y = "U2_VALUE_X";
# use MACRO_SPEC
my $USER2 = (
  u2key1 => "u2value1",
  u2macrokey => $MACRO_SPEC,  # need macro to interpolate 'local' $v_Y 
);


#this is how USER1 should look after the interpolation
my $USER1 = (
  u1key1 => "u1value1",
  u1macrokey => { 
                  mkeyX   => "value_X",
                  mkeyY   => "U1_VALUE_X"
                },
);
#this is how USER2 should look after the interpolation
my $USER2 = (
  u2key1 => "u2value1",
  u1macrokey => {
                  mkeyX   => "value_X",
                  mkeyY   => "U2_VALUE_X"
                },
);
1

There are 1 answers

0
mob On BEST ANSWER

Like melpomene suggested, you want $MACRO_SPEC to be a function that can generate something different each time it is called.

package One;
our $v_Y;
my $MACRO_SPEC = sub { +{ mkeyX => "value_X", mkeyY => $v_Y } };

...

package USER1;
$One::v_Y = "U1_VALUE_X";
my $user1 = {          # { }, not ( ), to define a hash reference
    u1key1 => "u1value1", 
    u1macrokey => $MACRO_SPEC->(),   # $f->() to exec code defined in $f
    ...
};