2012-07-12 55 views
1

可能重复:
How do I break out of a loop in Perl?的Perl - 停止读取一个文件,如果多行匹配

我有数据,看起来就像你所看到的波纹管。我正在尝试创建一个将捕获选定文本的perl脚本。我的想法是说“如果上一行读取全是 - 并且当前行读取全部=',那么请停止阅读文件,并且不要仅用=和 - 打印这些行

但是,我不知道如何编写代码,我只是在3天前开始使用perl,我不知道这是否是最好的方式,让我知道是否有更好的方法如果 无论哪种方式,你可以用代码的帮助,我会很感激的

到目前为止我的代码:

... 
$end_section_flag = "true" # I was going to use this to signify 
          # when I want to stop reading 
          # ie. when I reached the end of the 
          # data I want to capture 

while (<$in-fh>) 
{ 
    my $line = $_; 
    chomp $line; 

    if ($line eq $string) 
    { 
     print "Found it\n"; 
     $end_section_flag = "false"; 
    } 

    if ($end_section_flag eq "false") 
    { 
     print $out-fh "$line\n"; 
     // if you found the end of the section i'm reading 
     // don't pring the -'s and ='s and exit 
    } 
} 

什么我的数据看起来像

------------------------------------------------------------------------------- 
=============================================================================== 
BLAH BLAH 
=============================================================================== 
asdfsad 
fasd 
fas 
df 
asdf 
a 
\n 
\n 
------------------------------------------------------------------------------- 
=============================================================================== 
BLAH BLAH 
=============================================================================== 
... 

我想捕捉,因为你的边界跨越行尾

------------------------------------------------------------------------------- 
=============================================================================== 
BLAH BLAH 
=============================================================================== 
asdfsad 
fasd 
fas 
df 
asdf 
a 
\n 
\n 
+0

您没有以粗体显示任何文本。 – Borodin 2012-07-12 14:58:05

+0

[我如何摆脱Perl中的循环?](http://stackoverflow.com/questions/303216/how-do-i-break-out-of-a-loop-in-perl) – 2012-07-12 14:58:31

+0

真实世界例子应该有所帮助从你的问题不清楚你想要达到什么。显示:1)你有什么2)和你想得到什么3)变成什么变量。你的代码没有关于内容的任何条件 - “$ end_section_flag”还没有任何说明。 – jm666 2012-07-12 14:58:45

回答

1

线路明智的处理是不是所以适合什么。整个文件夹,然后用匹配运算符提取中间文件。

use strictures; 
use File::Slurp qw(read_file); 
my $content = read_file 'so11454427.txt', { binmode => ':raw' }; 
my $boundary = qr'-{79} \R ={79}'msx; 
my (@extract) = $content =~ /$boundary (.*?) $boundary/gmsx; 
+0

我是Perl新手,请介意解释代码吗? 谢谢:) – Ryan 2012-07-12 15:17:53

+0

我将文件内容读入字符串变量。然后我定义边界,79破折号和一些换行符和79等于。然后我匹配内容字符串的边界和中间的边界。我捕获中间并将其分配给一个变量。 – daxim 2012-07-12 16:19:25

0

看看这个适合你的需要:

perl -ne 'm/^---/...m?/---/ and print' file 

,你应该只想要第一个块,改变分隔符从/?正是如此:

perl -ne 'm?^---?...m?^---? and print' file 

range运营商讨论。

这将打印由'---'限定的行范围。您可以使用shell的重定向将输出重定向到您选择的文件中:

perl -ne 'm/^---/...m?/---/ and print' file > myoutput 
+0

我不明白这段代码。它在哪里?它如何适应?它在做什么?对不起,我还是Perl的新手。我很感激澄清。 – Ryan 2012-07-12 15:29:29

相关问题