Do I need to reset the Perl hash index?

OK, this is question N00b, but it puzzled me:

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_codealways transmitted in the same ('dis'), and the print line shows this.

However, every time I run this, I get a different value for project_keys{$key}.

What (no doubt the obvious) that I am doing wrong? I saw comments about how each “fragile” is what?

+2
source share
3 answers

If you already have the "key" that you expect, check to see if it exists and uses 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
+6
source

, each , , , , .

reset , :

keys(%project_keys);
while ( ($key, $value) = each %project_keys ) {

, :

eq, == .

; , ; :

if ( exists $project_keys{$proj_code} ) {
    $url = "http://projects/$project_keys{$proj_code}";
}
+3

You are using each. Better not do it. It is thin and keeps state in a hash.

Much better than

while( my ( $key, $value ) = each %hash ) {
   ...
}

is to use a loop foreachfor a functionkeys

foreach my $key ( keys %hash ) {
   my $value = $hash{$key};
   ...
}
0
source

Source: https://habr.com/ru/post/1531266/


All Articles