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

Hi,

I would like to dereference a Hash of Hash within a string.

Normally I do it like this

print "MyText${var}ishere";

How can I use the brackets when dereferecing a Hash of hash?

This does not work:

print "MyText${ref_HoH}->{$var}->{key}ishere."

print "MyText${ref_HoH->{$var}->{key}}ishere."

This works but I think this not a very good way ...

print "MyText$ref_HoH->{$var}->{key}ishere."

Thanks for help.

regards de Michi

Replies are listed 'Best First'.
Re: Dereference Hash of Hash - print
by LanX (Saint) on Oct 12, 2014 at 21:13 UTC
    > This works but I think this not a very good way ...

    It is, but you can avoid one arrow

    print "MyText$ref_HoH->{$var}{key}ishere."

    You can also try (untested)

    print "MyText$$ref_HoH{$var}{key}ishere."

    Anyway I'd prefer something more readable, so why interpolating?

    update

    This looks like an XY problem, do you really need 2 levels?

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

Re: Dereference Hash of Hash - print
by Athanasius (Archbishop) on Oct 13, 2014 at 03:10 UTC

    Hello demichi,

    I agree with LanX, readability is the key here. Consider the following, which all print MyTextWilmaishere.:

    #! perl use strict; use warnings; my $ref_HoH = { Fred => { wife => 'Wilma', daughter => 'Pebbles', }, Barney => { wife => 'Betty', son => 'Bamm-Bamm', }, }; my $var = 'Fred'; my $key = 'wife'; print "MyText$ref_HoH->{$var}{$key}ishere.\n"; # interpol +ated print "MyText$$ref_HoH{$var}{$key}ishere.\n"; # interpol +ated print "MyText" . $ref_HoH->{$var}{$key} . "ishere.\n"; # concaten +ated print "MyText" . $$ref_HoH{$var}{$key} . "ishere.\n"; # concaten +ated printf "MyText%sishere.\n", $ref_HoH->{$var}{$key}; # template +d printf "MyText%sishere.\n", $$ref_HoH{$var}{$key}; # template +d

    My preference is for printf, which presents the complete structure of the output up-front, in the format string; but concatenation is always a valid option; and either option is clearer, and therefore more maintainable, than the equivalent interpolation.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,