2014-11-20 4 views
0

다른 파일 (rangefile)과 일치하는 한 파일 (DATA)의 행 범위를 주석 처리 (실제로는 다른 파일로 인쇄)합니다. 나는 2, 3, 4, 7, DATA에서 8 일치 내가 주석 할 줄파일의 다른 범위의 값을 주석으로 처리 - Perl

2 4 
7 8 

에 다음 한 경우 rangefile는, 즉, 행 방향이다. 는 내가 지금까지 가지고하는 것은 이것이다 :

#!/usr/bin/perl 

use warnings; 
use strict; 

my $rangefile = $ARGV[0]; 

open (RANGE, $rangefile) or die "Couldn't open $rangefile: $!\n"; 
my %hash; 
while (<RANGE>) { 
     my ($begin, $end) = split;; 
     $hash{$begin} = $end; 
} 
close RANGE; 

my %seen; 
while (<DATA>) { 
     if (/^[^\d]/) { next } 
     # just split into an array because this file can have several fields 
     # but want to match 1st field 
     my @array = split;  

     foreach my $key (keys %hash) { 
       my $value = $hash{$key}; 
       if ($array[0] >= $key && $array[0] <= $value) { 
         unless ($seen{$array[0]} ++) { 
           print "#$_"; 
         } 
       } 
       else { 
         unless ($seen{$array[0]} ++) { 
           print; 
         } 
       } 
     } 
} 

__DATA__ 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

그러나이 코드 중 하나를 인쇄 # 2, # 3, # 4, # 7, # 8 만 모두 함께 범위를하지 않습니다. 구인 출력 :

1 
#2 
#3 
#4 
5 
6 
#7 
#8 
9 
10 

답변

2

귀하의 %hash 실제로 키를 사용 #

#!/usr/bin/perl 

use warnings; 
use strict; 

# my %hash = (2,4,7,8); 
my ($rangefile) = @ARGV; 

open (my $RANGE, "<", $rangefile) or die "Couldn't open $rangefile: $!\n"; 
my %hash; 
while (<$RANGE>) { 
     my ($begin, $end) = split; 
     @hash{$begin .. $end} =(); 
} 
close $RANGE; 

while (<DATA>) { 
     my ($num) = /^(\d+)/ or next; 
     s/^/#/ if exists $hash{$num}; 
     print; 
} 

__DATA__ 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
+0

와 접두사 할 (숫자) 예,이 영리한 솔루션을 보인다 개최한다. – PedroA