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

Hi Monks!

Trying to get the value based on a key from a hash:
my $search = "home"; my %name = ( 'home' => ['main', '100 - Main Street'], 'rent' => ['travel', 'Other State'], ); print $name->{$search}[0][0];

Thanks for helping?

Replies are listed 'Best First'.
Re: Print value from hash
by davido (Cardinal) on Sep 25, 2015 at 19:00 UTC

    This answer and more can be found in perlintro -- a 20 minute read. To save time for this specific task (at the expense of leaving other questions unanswered), skip to perlintro#Perl-variable-types. Hashes are discussed there, and examples exist on how to index into a hash.

    In your specific code example, you are dereferencing a scalar named $name as if it contains a reference to a hash. And presumably you are getting a strict violation at compile time because no variable, "$name" exists. %name is a first class hash, and elements are accessed via direct index rather than dereferencing: $name{$search}[0] would return 'main'. $name{$search} would return a reference to the array that contains 'man', and '100 - Main Street'.

    Handling references is introduced in perlreftut.


    Dave

Re: Print value from hash
by mhearse (Chaplain) on Sep 25, 2015 at 19:01 UTC
    Your code declares a hash of arrays:
    print $name{$search}[0], "\n";
    or
    my @array = @{$name{$search}};

      Not taking away from your insight, but I think it's important for future readers of any code to see where de-referencing begins.

      perl always knows when anything in a (hash) structure is another structure and allows you to not require the deref operator (->) because it's implicit, but I'd recommend putting such in the path where dereferencing starts:

      print "$name{$search}->[0]\n";

      Easier to spot where things become a reference at a glance.

      -stevieb

Re: Print value from hash ( Data::Diver)
by Anonymous Monk on Sep 25, 2015 at 23:28 UTC

    See Data::Diver and references quick reference

    #!/usr/bin/perl -- use strict; use warnings; use Data::Dump qw/ dd /; use Data::Diver qw/ Dive /; my $plot = { 'home' => ['main', '100 - Main Street'], 'rent' => ['travel', 'Other State'], }; my $of = "home"; print $plot->{ $of }[0], "\n"; print Dive( $plot, $of, 0 ) , "\n"; __END__ main main