2009-04-22 8 views

답변

9

홀수 요청,하지만 그것을 수행해야합니다

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

대신 어떻게 마지막 5 줄에 하나를 적용할까요? – Tanami

+0

my ($ last_five_lines) = $ s = ~ /((-)(n){5})\z/; –

+0

{0,5} 수식어가 필요합니다. 그렇지 않으면 4 줄의 문자열을 거부합니다 (원하는 경우가 아니면). –

6

head을 사용하지 않으시겠습니까?

+0

이 큰 문자열 내부 인 경우 펄 프로그램이고 임시 파일을 만들고 싶지 않다면 그렇게 할 수 없습니다. –

+0

@brian d foy 흠, 사실이 아닙니다. 양방향 파이프를 열 수 있습니다. 그것은 어리석은 일이지만, 당신은 그것을 할 수 있습니다. –

+1

양방향 파이프를 열 수 있습니까? Perl은 많은 장소에서 실행됩니다. :) –

2
my ($first_five) = $s =~ /\A((?:.*\n){5})/; 
my ($last_five) = $s =~ /((?:.*\n){5})\z/; 
2

, 당신이 사용할 수있는 head 또는 tail 어느 쪽의 문제 (처음 5 행 또는 마지막 5 행)에 대해 꽤 쉽게.

하지만 이제는 질문을 올바르게 이해하는지 궁금합니다. "어떤 종류의 스칼라에 대해서"라고 말할 때, 어떤 이유로 파일이 이미 스칼라에 있다는 것을 의미합니까?

그렇지 않다면 가장 좋은 해결책은 전혀 정규식이 아니라고 생각합니다. $.을 사용하고 파일을 정상적으로 읽거나 거꾸로 읽으십시오. 뒤로 읽으려면 File::ReadBackwards 또는 File::Bidirectional을 시도해보십시오.

+0

파일 :: ReadBackwards는 파일이 매우 길면 좋습니다. –

1

사람들은 몇 가지 주요 플래그를 누락 : 멀티 라인 플래그없이

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

, 첫 번째 줄에서 보는 것입니다. 또한 \n을 선택적으로 만들면 다섯 번째 끝의 개행에 관계없이 처음 다섯 개를 개로 가져갈 수 있습니다.

3

정규식이 필요하지 않습니다.

my $scalar = ...; 

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

$scalar = join '', @lines; 
+0

브라이언 - 오픈() 호출에서 $ fh를 두 번 참조하는 오타가 아닙니까? – Alnitak

1

가 왜 그냥 한계와 분할을 사용, 그것은이 목적을 위해 설계 :

그냥 스칼라에 대한 참조에 파일 핸들을 열은 다음 파일 핸들의 다른 종류에 대한 것과 같은 일을 할
my @lines = (split /\n/, $scalar, 6)[0..4]; 

다섯 줄 하나의 스칼라로 그것을 다시 원하는 경우까지를 다시 조인

my $scalar = join('\n', @lines) . "\n"; 
0
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]"); 
} 
관련 문제