从任何类型的标量,我可以使用什么正则表达式来匹配它的前五行并丢弃其余的?
解决方法
奇怪的请求,但这应该这样做:
#!/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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。