How do I pass a variable as a method to a Perl hash reference?
This isn't generally possible, but there are workarounds:
do a string-
eval
:my $val = do { local $@; my $val = eval "\$decoded_json->$datapath"; die $@ if $@; $val;};
Of course, using
eval
in this way is frowned upon.Define a function that walks a data structure:
sub walk { my $data = shift; while (@_) { my $index = shift; if (ref $data eq 'HASH') { $data = $data->{$index}; } elsif (ref $data eq 'ARRAY') { $data = $data->[$index]; } else { die qq(Wanted to use index "$index", but "$data" is neither hash nor array); } } return $data;}my $val = walk($decoded_json, 0, 'data', 0, 0);
Of course, this would fail with overloaded objects.