Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to reset a Perl hash index?

Tags:

hash

perl

OK, this is a N00b question, but it's gotten me stumped:

I have the following Perl code:

%project_keys = (
  cd     => "continuous_delivery",
  cm     => "customer_management",
  dem    => "demand",
  dis    => "dis",
  do     => "devops",
  sel    => "selection",
  seo    => "seo"
);

print "proj_code is $proj_code\n";
while ( ($key, $value) = each %project_keys ) {
    if ($key == $proj_code) {
        $url = "http://projects/".$project_keys{$key}."/setter";
        last;
    }
}

$proj_code is always passed in the same ('dis') and the print line shows that.

However, each time I run this, I'm getting a different value for project_keys{$key}.

What (no doubt obvious) thing am I doing wrong? I have seen comments about how each is 'fragile' - is that it?

like image 327
roryhewitt Avatar asked Dec 29 '25 10:12

roryhewitt


1 Answers

If you already have the "key" you're expecting, check if it exists and use it...

Also, always use use strict; use warnings;

#!/usr/bin/perl

use strict;
use warnings;

my $proj_code= 'dis';
my $url;

my %project_keys = (
  cd     => "continuous_delivery",
  cm     => "customer_management",
  dem    => "demand",
  dis    => "dis",
  do     => "devops",
  sel    => "selection",
  seo    => "seo"
);

$url = "http://projects/$project_keys{$proj_code}/setter" 
    if exists $project_keys{$proj_code};

print "url: $url\n";

OUTPUTS:

url: http://projects/dis/setter
like image 60
chrsblck Avatar answered Dec 30 '25 23:12

chrsblck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!