简体   繁体   English

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

[英]Perl include continuation lines and ignore double quotes

I was working on a script that needs to produce foo for the first two lines and bar for the last three. 我正在编写一个脚本,该脚本需要在前两行中生成foo ,在后三行中生成bar There are two issues i am running into here. 我在这里遇到两个问题。

  1. How do I get Perl to ignore the double quotes around the first foo? 如何让Perl忽略第一个foo周围的双引号?

  2. How do I get it recognize the backslash as a continuation line? 如何获得将反斜杠识别为续行的信息? - -

Sample input: 输入样例:

reset -name "foo"
quasi_static -name foo
reset \
-name bar
set_case_analysis -name "bar"

My Code: 我的代码:

   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";
    }

If you're going through a file line by line, you can keep partial lines in a variable and concatenate them with the next line. 如果要逐行浏览文件,则可以将部分行保留在变量中,然后将它们与下一行连接起来。 Read through the code - I have commented the functionality. 通读代码-我已经评论了该功能。

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 = '';
}

You could make it more compact and neat by doing something like this: 通过执行以下操作,可以使其更紧凑,更整洁:

if ( $curr =~ /(\w+) -name \"?(\S+)/) {
      ( $txt = $2 ) =~ s/"$//;
      $data{$1}{$txt}=1;
}

You would get a nested hash structure with the three keys, set_case_analysis , quasi_static , and reset , and the various different values from -name . 您将获得带有三个键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 )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM