我的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
语句?
答案 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];
}