문제

어떤 종류의 스칼라에서, 나는 그것의 처음 5 줄에 맞추고 나머지를 버리는 데 어떤 정규식을 사용할 수 있습니까?

도움이 되었습니까?

해결책

홀수 요청이지만 그렇게해야합니다.

#!/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, 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;

다른 팁

그냥 사용하지 않는 이유는 무엇입니까? head 그에 대한?

regex가 필요하지 않습니다. 스칼라를 참조하여 파일 핸들을 열고 다른 종류의 파일 핸들에 대해 동일한 작업을 수행하십시오.

my $scalar = ...;

open my($fh), "<", \ $scalar or die "Could not open filehandle: $!";
foreach ( 1 .. 5 )
    {
    push @lines, scalar <$fh>;
    }
close $fh;

$scalar = join '', @lines;
my ($first_five) = $s =~ /\A((?:.*\n){5})/;
my ($last_five) = $s =~ /((?:.*\n){5})\z/;

Brian이 말했듯이, 당신은 사용할 수 있습니다 head 또는 tail 문제에 대해 쉽게 쉽게 쉽게 쉽게 쉽게 쉽게 쉽게 쉽게 빠져 나와 있습니다 (첫 5 줄 또는 마지막 5 줄).

그러나 지금 나는 당신의 질문을 올바르게 이해하는지 궁금합니다. "어떤 종류의 스칼라"라고 말할 때, 당신은 (어떤 이유로 든) 파일이 이미 스칼라에 있다는 것을 의미합니까?

그렇지 않다면, 최상의 솔루션은 전혀 정규식이 아니라고 생각합니다. 사용 $. 파일을 정상적으로 또는 뒤로 읽습니다. 거꾸로 읽으려면 시도해 볼 수 있습니다 File::ReadBackwards 또는 File::Bidirectional.

사람들은 몇 가지 주요 깃발을 놓치고 있습니다.

/(?m)((?:^.*\n?){1,5})/

멀티 라인 플래그가 없으면 첫 번째 줄만 보게 될 것입니다. 또한 \n 선택 사항, 우리는 처음 5 개를 가져갈 수 있습니다 윤곽, 다섯 번째 끝에 새로운 라인에 관계없이.

한계와 함께 분할을 사용하지 않겠습니까?이 목적을 위해 설계되었습니다.

my @lines = (split /\n/, $scalar, 6)[0..4];

5 줄의 단일 스칼라로 다시 원한다면 다시 연결하십시오.

my $scalar = join('\n', @lines) . "\n";
use strict;


my $line; #Store line currently being read
my $count=$ARGV[1]; # How many lines to read as passed from command line
my @last; #Array to store last count lines
my $index; #Index of the line being stored


#Open the file to read as supplied from command line
open (FILE,$ARGV[0]);
while ($line=<FILE>)
{
    $index=$.%$count;  # would help me in filter just $count records of the file
    $last[$index]=$line; #store this value
}
close (FILE);

#Output the stored lines
for (my $i=$index+1;$i<$count;$i++)
{
    print ("$last[$i]");
}
for (my $i=$0;$i<=$index;$i++)
{
    print ("$last[$i]");
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top