Perl 包含连续行并忽略双引号

Perl include continuation lines and ignore double quotes

提问人:synarchy007 提问时间:8/8/2018 最后编辑:synarchy007 更新时间:8/9/2018 访问量:254

问:

我正在编写一个脚本,需要为前两行生成 foo,为后三行生成 bar。我在这里遇到了两个问题。

  1. 如何让 Perl 忽略第一个 foo 周围的双引号?

  2. 如何让它将反斜杠识别为延续行?-

输入示例:

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";
    }
Perl 引号行 延续

评论

0赞 i alarmed alien 8/8/2018
您是否正在从文件中逐行读取此数据?行延续字符是否总是出现在同一个地方?
0赞 synarchy007 8/8/2018
是的,正在逐行读取数据。行延续字符并不总是出现在同一列文本中,但当它出现时,它位于行的最后一个空格上。@ialarmedalien

答:

0赞 i alarmed alien 8/8/2018 #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_analysisquasi_staticreset-name

%data = (
  quasi_static => ( foo => 1, bar => 1 ),
  reset => ( pip => 1, pap => 1, pop => 1 ),
  set_case_analysis => ( foo => 1, bar => 1 )
);

评论

0赞 synarchy007 8/9/2018
我对 perl 很陌生,所以我对正则表达式有点迷茫,但是我能够跟上。我不断收到“需要特定包名称”的错误。我需要导入任何软件包吗?
0赞 i alarmed alien 8/9/2018
以上都是普通的 Perl,无需任何特殊设置即可工作。是否有其他代码可能导致错误?你能发布完整的错误消息吗?
0赞 synarchy007 8/10/2018
我目前在上面发布的第一段代码的括号周围遇到语法错误。我应该删除它,因为它所做的只是将值推送到变量?这难道不是你的编辑所做的吗?