if (CONDITION_1) {
if (CONDITION_A) {
a = 1;
}
}
elsif (CONDITION_2) {
if (CONDITION_B) {
if (CONDITION_i) {
a = 2;
}
elsif (CONDITION_ii) {
a = 3;
}
endif
}
endif
}
endif
我想提取出來作爲字符串的條件,並根據自己的水平一樣將它們打印出來:提取IF-ELSIF根據自己的水平條件
CONDITION_1
CONDITION_1//CONDITION_A
CONDITION_2
CONDITION_2//CONDITION_B
CONDITION_2//CONDITION_B//CONDITION_i
CONDITION_2//CONDITION_B//CONDITION_ii
我應該如何在Perl遞歸代碼時,因爲真正的文件可能有超過3個級別的if-else塊?我無法設法使邏輯正確。非常感謝。
---------- ----------編輯
我想通了這背後的邏輯,這是我的工作代碼:
my (%cond, $lvl);
open my $fh, '<', $file or die;
while (<$fh>) {
if (/if\s\((\w+)\)/) {
$lvl++;
push @{ $cond{$lvl} }, $1;
for my $i (1 .. $lvl) {
print "${ $cond{$i} }[-1]";
print "//" if $i != $lvl;
}
print "\n";
}
elsif (/elsif\s\((\w+)\)/) {
push @{ $cond{$lvl} }, $1;
for my $i (1 .. $lvl) {
print "${ $cond{$i} }[-1]";
print "//" if $i != $lvl;
}
print "\n";
}
elsif (/else/) {
push @{ $cond{$lvl} }, 'else';
for my $i (1 .. $lvl) {
print "${ $cond{$i} }[-1]";
print "//" if $i != $lvl;
}
print "\n";
}
elsif (/endif/) {
$lvl--;
}
}
close $fh;
什麼是「東西」?爲了可靠地做到這一點,你需要能夠解析一切,而不僅僅是你想要的東西。 – ysth
它們只是定義的聲明,如'define CONSTANT 3'。然而,if塊的內容並不重要,因爲我只需要提取條件。對於那個很抱歉。 –
是否始終絕對一致的縮進呢?並始終是空格,而不是標籤? – ysth