多个if-else语句混淆perl

chr*_*yyy 3 perl

我的if-else语句有问题.即使$key我正在使用我的if语句中的文本匹配,else我在底部的语句也被评估,所以我得到每个的多个值$key,这是一个问题.我在这做错了什么?

my $key = $line[0];
if ($key eq 'this_setting') {
    my $counter1 = $counter + 1;
    my $counter2 = $counter + 2;
    $value = join(' ', @line[$counter1..$counter2]);                        
    $my_setting_hash{$key} = $value;
}
if ($key eq 'some_setting_abc') {
    my $counter1 = $counter + 1;
    my $counter2 = $counter + 2;
    $value = join(' ', @line[$counter1..$counter2]);
    $my_setting_hash{$key} = $value;
}
if ($key eq 'another_setting_123') {
    my $counter1 = $counter + 1;
    my $counter3 = $counter + 3;
    $value = join(' ', @line[$counter1..$counter3]);
    $my_setting_hash{$key} = $value;
}       
else {
    my $counter1 = $counter + 1;
    $value = $line[$counter1];
    $my_setting_hash{$key} = $value;
}
Run Code Online (Sandbox Code Playgroud)

else如果我的一个if陈述被评估,为什么不绕过这个陈述?

Ted*_*opp 10

您需要将它们链接在一起elsif:

my $key = $line[0];
if ($key eq 'this_setting') {
    my $counter1 = $counter + 1;
    my $counter2 = $counter + 2;
    $value = join(' ', @line[$counter1..$counter2]);                        
    $my_setting_hash{$key} = $value;
}
elsif ($key eq 'some_setting_abc') {
    my $counter1 = $counter + 1;
    my $counter2 = $counter + 2;
    $value = join(' ', @line[$counter1..$counter2]);
    $my_setting_hash{$key} = $value;
}
elsif ($key eq 'another_setting_123') {
    my $counter1 = $counter + 1;
    my $counter3 = $counter + 3;
    $value = join(' ', @line[$counter1..$counter3]);
    $my_setting_hash{$key} = $value;
}       
else {
    my $counter1 = $counter + 1;
    $value = $line[$counter1];
    $my_setting_hash{$key} = $value;
}
Run Code Online (Sandbox Code Playgroud)

否则,前两个if语句独立于第三个if/ else语句.


Mil*_*ler 6

正如已经指出的那样,您需要关键字elsif

但是,另一种解决方案是将每个密钥的特殊规则放入哈希中,以便共享代码:

my %key_length = (
    this_setting        => 1,
    some_setting_abc    => 1,
    another_setting_123 => 2,
);

my $key = $line[0];

my $index_low = $counter + 1;
my $index_high = $index_low + ($key_length{$key} // 0);

$my_setting_hash{$key} = join ' ', @line[ $index_low .. $index_high ];
Run Code Online (Sandbox Code Playgroud)