jeanluca has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

Here is an example of what I would like to do:
$a = { a1 => { a2 => 'Hi' } } ; $my_key = "a1\{a2\}" ; print "Hash-value is $a->{$my_key}\n" ;
Is something like this possible ?

Thanks in advance
Luca

Replies are listed 'Best First'.
Re: hash-value access via special constructed key
by holli (Abbot) on Mar 07, 2006 at 12:50 UTC
    You could surely do something like that using Tie::Hash, but why not using a lookup function?
    my $hash = { a1 => { a2 => 'Hi' } }; my @key = qw {a1 a2}; print "Hash-value is ", lookup($hash, @key), "\n"; sub lookup { my $hash = shift; my $key = shift; return @_ ? lookup($hash->{$key}, @_) : $hash->{$key}; }


    holli, /regexed monk/
      very nice solution.....

      Luca
Re: hash-value access via special constructed key
by davorg (Chancellor) on Mar 07, 2006 at 12:29 UTC

    You can probably do something along those lines using eval, but it's really not a good idea. If you explain a bit more about your problem then we can probably help find a better solution.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: hash-value access via special constructed key
by jeanluca (Deacon) on Mar 07, 2006 at 12:47 UTC
    Sure no problem.
    The problem is that I have a hash (inside a hash etc). I also have the key like: $my_key = "\{a1\}\{a2\}" ;
    That is the situation.
    I can use a regexp to split $my_key into an array an than extract the value from the hash via a for-loop, but it would be easier if I could directly insert $my_key into the hash, like $mh-{$my_key} or $mh->$my_key (but now $my_key is a method)

    Hopefully this helps!