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

Hi,

I have a piece of code as this:

my %cliParms; var_b = subA(\%cliParms); print Dumper(%cliParms);

from Dumper, I see cliParms seems to be a hash for hash:

VAR1 = 'tclDefs'; VAR2 = { 'my_var1' => 'a', 'my_var2' => 'b' }

I would like to get value from VAR2, so I wrote code as this:

my %my_tcldefs; %my_tcldefs = $cliParms->{'tclDefs'}; print Dumper(%my_tcldefs);

It seems I failed to get my_tcldefs. Can anybody help me? thanks.

Replies are listed 'Best First'.
Re: help on reference to hash
by davido (Cardinal) on Jun 21, 2014 at 07:41 UTC

    You seem to want this:

    my %my_tcldefs = %{$cliParms->{'tclDefs'}};

    Your Data::Dumper dump would be easier to understand if you invoked it like this:

    print Dumper \%cliParms;

    Then the output would be something like this:

    $VAR1 = { 'tcl_defs' => { my_var1 => 'a', my_var2 => 'b' } };

    ...which makes it more obvious that 'tcl_defs' is a key with a value that consists of a reference to another anonymous hash.


    Dave

      my %my_tcldefs = %{$cliParms->{'tclDefs'}};

      The expression  $cliParms->{'tclDefs'} treats  $cliParms as a hash reference rather than as a hash as shown on the OPed code. Fixing that and the key name tyop (and using Dumper properly :) gives:

      c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le "my %cliParms = ( tclDefs => { my_var1 => 'a', my_var2 => 'b' }, ); print Dumper \%cliParms; ;; my %my_tcldefs = %{ $cliParms{tclDefs} }; print Dumper \%my_tcldefs; " $VAR1 = { 'tclDefs' => { 'my_var2' => 'b', 'my_var1' => 'a' } }; $VAR1 = { 'my_var2' => 'b', 'my_var1' => 'a' };

      Update: skyworld_chen: The expression  $cliParms->{'tclDefs'} assumes the existence of a scalar  $cliParms that has been assigned a hash reference, which is evidently not the case in your code. Had you enabled warnings and, in particular, strictures (see strict), you might have had "more guidance" from Perl itself in the form of a "Global symbol "$cliParms" requires explicit package name ..." message (followed by the failure of the code to compile).

        Hi

        this works, thanks very much. I'm sure I misunderstood the reference, hash etc. Is there any recommended pages on explaining these? thanks.

      Hi Dave,

      thanks for your kind reply. I have tried the code, but it seems I have some problem on this piece of code:

      my %my_tcldefs = %{$cliParms->{'tclDefs'}};

      there is no value passed to %my_tcldefs and %my_tcldefs is empty. Could you please give me more guidance? thanks very much!

        That's because it should be tcl_defs, not tclDefs:

        my %my_tcldefs = %{$cliParms->{'tcl_defs'}};

        EDIT: for the benefit of later readers and to avoid confusion, when I wrote this reply, the original question (since edited, apparently) indeed said tcl_defs.