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


Hi Monks,

$ref = { "person" => { "name" => "Bob" } }; # this works print $ref->{person}{name}; # this doesn't $n = '{person}{name}'; print $ref->$n;

The error I get is "Can't call method on
unblessed reference"

How do i use variables while deferencing?

--
arc_of_descent

Replies are listed 'Best First'.
Re: variable interpolation while dereferencing
by Zaxo (Archbishop) on Oct 27, 2002 at 11:12 UTC

    You only need to have the variables evaluate to the keys. What you try doesn't give the compiler enough clues, it thinks the variable is to be the name of a method.

    my $top = 'person'; my $foo = 'name'; print $ref->{$top}{$foo};

    After Compline,
    Zaxo

      Hi,

      But i want to access the hash reference through a
      variable as i don't know how deep it may go!

      Like the following:

      sub add_folder("Linux/Kernel") { # i want to do the foll. # $bkref->{folder}{Linux}{folder}{Kernel}{folder} = {}; }

      So, the RHS may go to any size
      and i can't hard code it
      Can u help me out?

      --
      arc_of_descent

        As hint:

        my $path = 'A/B/C'; my $hr = { 'A' => {'B'=>{'C'=>'Hello'}}}; my @path = split m</>,$path; my $ref = $hr; while(@path){ $ref = $ref->{ shift @path } } print "$ref\n"
        --
        http://fruiture.de
Re: variable interpolation while dereferencing
by PodMaster (Abbot) on Oct 27, 2002 at 11:32 UTC
    The only way that would do what you want it to is with the use of eval
    $ref = { "person" => { "name" => "Bob" } }; # this works print $ref->{person}{name}; # this does $n = '{person}{name}'; eval 'print $ref->'.$n;
    I think Zaxo got your ticket though ;)

    update: Just because you've been shown you have to use a knife, doesn't mean you also have to be told "Hey, don't cut your fingers off."

    I did not forget, everybody knows its inherently dangerous.

    ____________________________________________________
    ** The Third rule of perl club is a statement of fact: pod is sexy.

      Your answer is certainly right, but please don't forget to point out all the madness that lies that way when you post something like that.

      Update: everyone knows things you can cut yourself with are dangerous. But not everyone knows which things you can cut yourself with, yet.

      Makeshifts last the longest.