加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 如何只保留Perl标量中的前五行?

发布时间:2020-12-14 06:06:56 所属栏目:百科 来源:网络整理
导读:从任何类型的标量,我可以使用什么正则表达式来匹配它的前五行并丢弃其余的? 解决方法 奇怪的请求,但这应该这样做: #!/usr/bin/perluse strict;use warnings;my $s = join '',map { "$_n" } 1 .. 9;my ($first) = $s =~ /^((?:.*n){0,5})/;my ($last) = $
从任何类型的标量,我可以使用什么正则表达式来匹配它的前五行并丢弃其余的?

解决方法

奇怪的请求,但这应该这样做:

#!/usr/bin/perl

use strict;
use warnings;

my $s = join '',map { "$_n" } 1 .. 9;

my ($first) = $s =~ /^((?:.*n){0,5})/;
my ($last) = $s =~ /((?:.*n){0,5})$/;


print "first:n${first}last:n$last";

一个更常见的解决方案是这样的:

#!/usr/bn/perl

use strict;
use warnings;

#fake a file for the example    
my $s = join '',map { "$_n" } 1 .. 9;    
open my $fh,"<",$s
    or die "could not open in memory file: $!";

my @first;
while (my $line = <$fh>) {
    push @first,$line;
    last if $. == 5;
}

#rewind the file just in case the file has fewer than 10 lines
seek $fh,0;

my @last;
while (my $line = <$fh>) {
    push @last,$line;
    #remove the earliest line if we have to many
    shift @last if @last == 6;
}

print "first:n",@first,"last:n",@last;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读