如何在Perl中阅读时跳过一些块内容

Nan*_* HE 1 perl expression

我打算跳过包含"MaterialiseU4()"起始行的块内容和read_block下面的subroutin().但失败了.

# Read a constant definition block from a file handle. 
# void return when there is no data left in the file. 
# Otherwise return an array ref containing lines to in the block.  
sub read_block { 
    my $fh = shift; 

    my @lines; 
    my $block_started = 0; 

    while( my $line = <$fh> ) { 

    # how to correct my code below? I don't need the 2nd block content.
 $block_started++ if ( ($line =~ /^(status)/) && (index($line, "MaterializeU4") != 0) ) ;

 if( $block_started ) { 

     last if $line =~ /^\s*$/; 

     push @lines, $line; 
 }

    } 
    return \@lines if @lines;
    return; 
} 
Run Code Online (Sandbox Code Playgroud)

数据如下:

__DATA__ 
status DynTest = <dynamic 100>
vid = 10002
name = "DynTest"
units   = ""

status VIDNAME9000 = <U4 MaterializeU4()>
vid = 9000
name = "VIDNAME9000"
units = "degC"

status DynTest = <U1 100>
vid = 100
name = "Hello"
units   = ""
Run Code Online (Sandbox Code Playgroud)

输出:

  <StatusVariables>
    <SVID logicalName="DynTest" type="L" value="100" vid="10002" name="DynTest" units=""></SVID>
    <SVID logicalName="DynTest" type="L" value="100" vid="100" name="Hello" units=""></SVID>
  </StatusVariables>
Run Code Online (Sandbox Code Playgroud)

[更新]我打印的值index($line, "MaterializeU4"),它的输出25.然后我更新了如下代码

$block_started++ if ( ($line =~ /^(status)/) && (index($line, "MaterializeU4") != 25)

现在它有效.

欢迎任何评论我的做法.

Axe*_*man 6

Perl已经有一个操作员来跟踪块.它被称为"触发器"运算符:

试试这个:

while ( <DATA> ) { 
   next if /\Q<U4 MaterializeU4()>\E/../^\s*$/;
   push @lines, $_;
}
Run Code Online (Sandbox Code Playgroud)

的值/\Q<U4 MaterializeU4()>\E/../^\s*$/将是真它看到一个起始正则表达式匹配线,它就会停止为真它看到一个线路匹配所述第二表达以后.

  • 参见[perlfaq6 - 如何在不同线条上的两个模式之间拉出线?](http://perldoc.perl.org/perlfaq6.html#How-can-I-pull-out-lines-between-双模式 - 即,是-本身-上不同线路%3f)的 (2认同)