fatih
fatih

Reputation: 349

How to get array element's value by given key in perl

I'm totally new in perl. I want to get element's value by its key from an associative array. my array is:

my %array = a.a.a.a => "my name",
       b.b.b.b => "my home",
       c.c.c.c => "my city";

when I print

print say %array<b.b.b.b>;
or 
print say %array{b.b.b.b};

it shows error, so how can I get this? code-test link: codepad link

Upvotes: 1

Views: 1976

Answers (4)

SES
SES

Reputation: 870

What you wrote is almost valid Perl6, with the only mistake being not quoting the keys. And that is only necessary in this example because .a and .b look like a method call in Perl6 and will generate undeclared subroutine warnings.

my %array =
   'a.a.a.a' => "my name",
   'b.b.b.b' => "my home",  
   'c.c.c.c' => "my city";

say %array<b.b.b.b>;
say %array{'b.b.b.b'};

Running this gives what you would expect:

$ perl6 hash.pl6
my home
my home

This example code looks more like Perl6 than Perl 5 to me, so I thought I would mention this for reference in case you were following a Perl6 tutorial and trying to compile the code with perl.

Upvotes: 2

Jens
Jens

Reputation: 69440

use :

my %array = ("a.a.a.a" => "my name",
       "b.b.b.b" => "my home",
       "c.c.c.c" => "my city");

print $array{"b.b.b.b"};

Upvotes: 1

newcoder
newcoder

Reputation: 494

use

print say $array{"b.b.b.b"};

or

print "$array{'b.b.b.b'}\n";

Upvotes: 0

Chankey Pathak
Chankey Pathak

Reputation: 21666

Associate arrays are called Hash in Perl.

Always use use strict; use warnings; in your Perl code. If you use it you will get to know that keys in your hash are not quoted.

#!/usr/bin/perl
use strict;
use warnings;

my %hash = (
        'a.a.a.a' => "my name",
        'b.b.b.b' => "my home",
        'c.c.c.c' => "my city"
    );

To access value of a key you do $hash{$key}, so to access b.b.b.b

print $hash{'b.b.b.b'};

Demo

Upvotes: 2

Related Questions