多个if-else语句混淆perl

时间:2015-07-30 00:19:09

标签: 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;
}

如果我的else语句之一被评估,为什么没有绕过此if语句?

3 个答案:

答案 0 :(得分: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;
}

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

答案 1 :(得分: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 ];

答案 2 :(得分:4)

假设$key的值为'some_setting_abc'。您的第一个if不适用,但第二个if适用。第三个if也不适用,但是其中一个else因此被执行。作为@TedHopp pointed out,您需要一个if代码elsif和一个else代替。

但是,我想指出代码中有很多重复。当您更简洁地编写代码时,生活会更简单:

my $key = $line[0];
my $index = $counter + 1;

if (($key eq 'this_setting') or ($key eq 'some_setting_abc')) {
    $my_setting_hash{$key} = join ' ', @line[$index .. ($index + 1)];
}
elsif ($key eq 'another_setting_123') {
    $my_setting_hash{$key} = join ' ', @line[$index .. ($index + 2)];
}       
else {
    $my_setting_hash{$key} = $line[$index];
}