How do I pass a variable as a method to a Perl hash reference? How do I pass a variable as a method to a Perl hash reference? json json

How do I pass a variable as a method to a Perl hash reference?


While it is possible to do that using eval, there are problems with that approach.

I suspect this is a better answer for your underlying problem:

use Data::Diver;my @datapath = ( 0, 'data', 0, 0 );print( Dumper( Data::Diver::Dive($decoded_json, @datapath) ));


This isn't generally possible, but there are workarounds:

  1. 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.

  2. 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.