Kalaiyarasan Selvaraj
Kalaiyarasan Selvaraj

Reputation: 17

How to pass variable as Key to hash in perl

my $host =`hostname | cut -c8-10`;
      my %envin = ('dev','dev','stg','stage','prd','prod');
      print $envin{'$host'};

Output :

Use of uninitialized value in print at host.pl line 7.

Unable to pass the variable as key to hash

Regards, kalai

Upvotes: 0

Views: 486

Answers (1)

Sobrique
Sobrique

Reputation: 53508

  • You're quoting $host with single quotes. It therefore won't be interpolated. You want $envin{$host} instead. $envin{"$host"} would work, but the quotes are redundant.
  • $host might have a linefeed. (chomp will fix)
  • usually a hash is more clearly written like this:

    my %envin = (
        'dev' => 'dev',
        'stg' => 'stage',
        'prd' => 'prod', 
    ); 
    

Upvotes: 6

Related Questions