你的問題很棘手,因爲你的限制並不精確。你說 - 我認爲 - 一個塊應該是這樣的:
foo,
bar,
baz)
哪裏foo
是啓動塊,和關閉括號結束它的字符串。但是,你也可以說:
foo bar baz) xxxxxxxxxxx,
你只想打印,直到)
,這是說foo bar baz)
,如果符合逗號結尾。
你可以也可以說,只有以逗號結尾的行應繼續:
foo, # print + is continued
bar # print + is not continued
xxxxx # ignored line
foo # print + is not continued
foo,
bar,
baz) # closing parens also end block
因爲我只能猜測你的意思是第一選擇,我給你兩個選擇:
use strict;
use warnings;
sub flip {
while (<DATA>) {
print if /^foo/ .. /\)\s*$/;
}
}
sub ifchain {
my ($foo, $print);
while (<DATA>) {
if (/^foo/) {
$foo = 1; # start block
print;
} elsif ($foo) {
if (/,\s*$/) {
print;
} elsif (/\)\s*$/) {
$foo = 0; # end block
print;
}
# for catching input errors:
else { chomp; warn "Mismatched line '$_'" }
}
}
}
__DATA__
foo1,
bar,
baz)
sadsdasdasdasd,
asda
adaffssd
foo2,
two,
three)
yada
第一個將打印從以foo
開始的行與以)
結尾的行之間找到的任何行。它會忽略「以逗號結束的行」限制。在積極的方面,它可以被簡化爲一個班輪:
perl -ne 'print if /^foo/ .. /\)\s*$/' file.txt
第二個是隻是一個簡單的,如果結構,這將考慮這兩種限制,並警告(打印到STDERR),如果它發現一個線在兩個不匹配的塊內。
來源
2012-05-29 00:45:14
TLP
顯示一些示例輸入和預期輸出。 – TLP