抓住Perl的文本

时间:2011-04-14 00:50:41

标签: perl

这是一个文本文件。

BEGIN:-----------------------------------------------
test 1
test 2 %%%%%%%%%%  TEST  TEST TEST
test 3
END:

我需要抓取代码BEGIN:END:之间的文字。

我怎么能用Perl以两种不同的方式做到这一点?

4 个答案:

答案 0 :(得分:3)

只需询问Perl文档:

  

如何在两者之间拉出线条   本身的模式   不同的行?

perldoc -q between

答案 1 :(得分:0)

这闻起来像家庭作业,所以我会给你一些方法快速给猫皮肤,但可能有更好的方法来做到这一点。

方法1

#!/usr/bin/perl
open FILE, "infile.txt"
# assuming bad formatting in the question and that BEGIN and END are on their own lines
my @text;
while (<FILE>)
   if ($_ =~ /BEGIN:/) {
       next;
   } else if ($_ =~ /END:/) {
       next;
   } else {
       push $_,@text;
   }
close FILE

@text是一个包含所有文本的数组

方法2(这实际上更适用于换行和回车)

#!/usr/bin/perl
$oldirs = $/;
$/='';  # set IRS to nothing
open FILE, "infile.txt";
$line = readline *FILE;
close FILE;
$line =~ s/BEGIN://g;
$line =~ s/END://g;
$/=$oldirs;

$line now contains all the text

答案 2 :(得分:0)

另一种选择......假设$foo中的文字......

$foo =~ /^BEGIN:([\S\s]+?)END:$/m;
result = $1;

OP的奖励积分......为什么$foo =~ /^BEGIN:(.+?)END:$/m无效?

答案 3 :(得分:0)

use common::sense;

local $/ = '';

my $file_content = <DATA>;

say $file_content;

say 'first result:';
say $file_content =~ /BEGIN:(.+?)END:/s;

say 'second result:';
my $begin = index($file_content,'BEGIN:') + 6;
my $end = index($file_content,'END:',$begin);

say substr($file_content,$begin,$end-$begin);

__DATA__
BEGIN:-----------------------------------------------
test 1
test 2 %%%%%%%%%%  TEST  TEST TEST
test 3
END: