Is there a clean way to, at declaration time, make a stored hash value point to another value in the same datastructure?
For example, say I have a datastructure for command callbacks:
my %commands = (
'a' => {
'init' => sub { return "common initializer"; },
'run' => sub { return "run a"; }
},
'b' => {
'init' => sub { return "init b"; },
'run' => sub { return "run b"; }
},
'c' => {
'init' => sub { return "common initializer"; },
'run' => sub { return "run c"; }
}
);
I know this could be rewritten as:
sub common_initializer() { return "common initializer"; }
my %commands = (
'a' => {
'init' => \&common_initializer,
'run' => sub { return "run a"; }
},
'b' => {
'init' => sub { return "init b"; },
'run' => sub { return "run b"; }
},
'c' => {
'init' => \&common_initializer,
'run' => sub { return "run c"; }
}
);
This works but the subroutines are no longer all anonymous. Double-initialization is another option:
sub get_commands($;$) {
my ($_commands, $pass) = @_;
%$_commands = (
'a' => {
'init' => sub { return "common initializer"; },
'run' => sub { return "run a"; }
},
'b' => {
'init' => sub { return "init b"; },
'run' => sub { return "run b"; }
},
'c' => {
'init' => $$_commands{'a'}{'init'},
'run' => sub { return "run c"; }
}
);
get_commands($_commands, 1) unless (defined $pass);
}
my %commands;
get_commands(\%commands);
This works but it's rather kludgy and expensive. I'm using subroutines in the example above but I'd like this to work for any datatype. Is there a cleaner way to do this in Perl?