简体   繁体   English

Perl:RegEx:在数组中存储变量行

[英]Perl: RegEx: Storing variable lines in array

I'm developing a Perl script and one of the script functions is to detect many lines of data between two terminals and store them in an array. 我正在开发一个Perl脚本,脚本功能之一是检测两个终端之间的多行数据并将它们存储在一个数组中。 I need to store all lines in an array but to be grouped separately as 1st line in $1 and 2nd in $2 and so on. 我需要将所有行存储在数组中,但要分别分组为$1第一行和$2第二行,依此类推。 The problem here is that number of these lines is variable and will change with each new run. 这里的问题是这些行的数量是可变的,并且每次新运行都会改变。

my @statistics_of_layers_var;
for( <ALL_FILE> ) {
   @statistics_of_layers_var = ($all_file =~ /(Statistics\s+Of\s+Layers)
   (?:(\n|.)*)(Summary)/gm );
   print @statistics_of_layers_var;

The given data should be 给定的数据应为

Statistics Of Layers
Line#1
Line#2
Line#3
...
Summary

How I could achieve it? 我该如何实现?

You can achieve this without a complicated regular expression. 您无需复杂的正则表达式即可实现此目的。 Simply use the range operator (also called flip-flop operator) to find the lines you want. 只需使用范围运算符 (也称为触发器运算符)来查找所需的行。

use strict;
use warnings;
use Data::Printer;

my @statistics_of_layers_var;
while (<DATA>) {
    # use the range-operator to find lines with start and end flag
    if (/^Statistics Of Layers/ .. /^Summary/) {
        # but do not keep the start and the end
        next if m/^Statistics Of Layers/ || m/^Summary/;
        # add the line to the collection
        push @statistics_of_layers_var, $_ ;
    }
}

p @statistics_of_layers_var;

__DATA__
Some Data
Statistics Of Layers
Line#1
Line#2
Line#3
...
Summary
Some more data

It works by looking at the current line and flipps the block on and off. 通过查看当前行并翻转该块来进行工作。 If /^Statistics of Layers/ matches the line it will run the block for each following line until the `/^Summary/ matches a line. 如果/^Statistics of Layers/匹配该行,它将为随后的每一行运行该块,直到`/ ^ Summary /匹配一行。 Because those start and end lines are included we need to skip them when adding lines to the array. 因为包含了这些开始和结束行,所以在向数组添加行时需要跳过它们。

This also works if your file contains multiple intances of this pattern. 如果您的文件包含该模式的多个实例,这也适用。 Then you'd get all of the lines in the array. 然后,您将获得数组中的所有行。

Maybe you can try this : 也许你可以试试这个:

push  @statistics_of_layers_var ,[$a] = ($slurp =~ /(Statistics\s+Of\s+Layers)
(?:(\n|.)*)(Summary)/gm );

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

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