簡體   English   中英

Perl:RegEx:在數組中存儲變量行

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

我正在開發一個Perl腳本,腳本功能之一是檢測兩個終端之間的多行數據並將它們存儲在一個數組中。 我需要將所有行存儲在數組中,但要分別分組為$1第一行和$2第二行,依此類推。 這里的問題是這些行的數量是可變的,並且每次新運行都會改變。

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;

給定的數據應為

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

我該如何實現?

您無需復雜的正則表達式即可實現此目的。 只需使用范圍運算符 (也稱為觸發器運算符)來查找所需的行。

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

通過查看當前行並翻轉該塊來進行工作。 如果/^Statistics of Layers/匹配該行,它將為隨后的每一行運行該塊,直到`/ ^ Summary /匹配一行。 因為包含了這些開始和結束行,所以在向數組添加行時需要跳過它們。

如果您的文件包含該模式的多個實例,這也適用。 然后,您將獲得數組中的所有行。

也許你可以試試這個:

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