Perl включает строки продолжения и игнорирует двойные кавычки
Я работал над сценарием, который должен производить foo для первых двух строк и строку для последних трех. Есть две проблемы, с которыми я сталкиваюсь здесь.
Как заставить Perl игнорировать двойные кавычки вокруг первого foo?
Как заставить его распознавать обратную косую черту как строку продолжения? -
Пример ввода:
reset -name "foo"
quasi_static -name foo
reset \
-name bar
set_case_analysis -name "bar"
Мой код:
if (/^\s*set_case_analysis.*\-name\s+(\S+)/)
{
$set_case_analysis{$1}=1;
print "Set Case $1\n";
}
elsif (/^\s*quasi_static.*\-name\s+(\S+)/)
{
$quasi_static{$1}=1;
print "Quasi Static $1\n";
}
elsif (/^\s*reset\s+.*\-name\s+(\S+)/)
{
$reset{$1}=1;
print "Reset $1\n";
}
1 ответ
Если вы просматриваете файл строка за строкой, вы можете сохранить частичные строки в переменной и объединить их со следующей строкой. Прочитайте код - я прокомментировал функциональность.
my $curr;
my $txt;
open ( IN, "<", 'yourinputfile.txt' ) or die 'Could not open file: ' . $!;
while (<IN>) {
chomp;
# if the line ends with a backslash, save the segment in $curr and go on to the next line
if ( m!(.*?) \$! ) {
$curr = $1;
next;
}
# if $curr exists, add this line on to it
if ( $curr ) {
$curr .= $_;
}
# otherwise, set $curr to the line contents
else {
$curr = $_;
}
if ( $curr =~ /set_case_analysis -name\s+\"?(\S+)/) {
# if the string is in quotes, the regex will leave the final " on the string
# remove it
( $txt = $1 ) =~ s/"$//;
print "Set Case $txt\n";
$set_case_analysis{$txt}=1;
}
elsif ($curr =~ /quasi_static -name\s+(\S+)/) {
( $txt = $1 ) =~ s/"$//;
print "Quasi Static $txt\n";
$quasi_static{$txt}=1;
}
elsif ($curr =~ /reset .*?-name\s+\"?(\S+)/) {
( $txt = $1 ) =~ s/"$//;
print "Reset $txt\n";
$reset{$txt}=1;
}
# reset $curr
$curr = '';
}
Вы можете сделать его более компактным и аккуратным, выполнив что-то вроде этого:
if ( $curr =~ /(\w+) -name \"?(\S+)/) {
( $txt = $2 ) =~ s/"$//;
$data{$1}{$txt}=1;
}
Вы бы получили вложенную хэш-структуру с тремя ключами, set_case_analysis
, quasi_static
, а также reset
и различные различные значения из -name
,
%data = (
quasi_static => ( foo => 1, bar => 1 ),
reset => ( pip => 1, pap => 1, pop => 1 ),
set_case_analysis => ( foo => 1, bar => 1 )
);