2014-07-25 53 views
0

我想比較@ arr3範圍的值與@ arr4範圍的值,但我沒有得到所需的輸出。請在下面的代碼中建議我修改以獲得輸出爲3,4,5,6,7,9,10,11,12,14,15(不重複示例5和10的值)並且總匹配= 11。如何比較2重疊的範圍沒有任何重複

文件1:結果

3..7 
9..12 
14..17 

文件2:註釋

1..5 
5..10 
10..15 

代碼:

#!/usr/bin/perl 
open ($inp1,"<result") or die "not found"; 
open ($inp2,"<annotation") or die "not found"; 
my @arr3=<$inp1>; 
my @arr4=<$inp2>; 
foreach my $line1 (@arr4) { 
    foreach my $line2 (@arr3) { 
     my ($from1,$to1)=split(/\.\./,$line1); 
      my ($from2,$to2)=split(/\.\./,$line2); 
    #print $from1;print "\n"; 

    for (my $i=$from1;$i<=$to1 ;$i++) { 
     for (my $j=$from2;$j<=$to2 ;$j++) { 
      if ($i==$j) { 
       print "$i";`enter code here`print "\n"; 
      } 
     } 
    } 
} 
+0

見[反轉的列表](http://www.perlmonks.org/?node_id=908453)。 – choroba

+0

從上一個問題中得到的答案有什麼問題? – fugu

回答

0

如果你的列表不是太大,你可以使用哈希,這是如何在Perl中實現「不重複」的最佳方式:

#!/usr/bin/perl 
use warnings; 
use strict; 

my @result = ('3..4', '9..12', '14..17'); 
my @annotation = ('1..5', '5..10', '10..15'); 

my %cmp; 
my $pass = 1; 
for my $range (@result, undef, @annotation) { 

    $pass = 2, next unless $range; 

    my ($from, $to) = split /\Q../, $range; 
    for my $num ($from .. $to) { 
     $cmp{$num} = $pass if 1 == $pass or $cmp{$num}; 
    } 
} 

my @output = sort { $a <=> $b } grep 2 == $cmp{$_}, keys %cmp; 
print join(',', @output), "\nTotal matched: ", scalar @output, "\n"; 
+0

在另一個文件中重複輸入失敗: my \ @result =('9..12','14 .17');我的\ @annotation =('1..5','5..10','10 ..15'); –

+0

@ColinPhipps:謝謝,修正。 – choroba

0

Works爲我

#!/usr/bin/perl 
    open ($inp1,"<result") or die "not found"; 
    open ($inp2,"<annotation") or die "not found"; 
    my @arr3=<$inp1>; 
    my @arr4=<$inp2>; 
    foreach my $line1 (@arr4) { 
      foreach my $line2 (@arr3) { 
        my ($from1,$to1)=split(/\.\./,$line1); 
        my ($from2,$to2)=split(/\.\./,$line2); 
        for (my $i=$from1;$i<=$to1 ;$i++) { 
          for (my $j=$from2;$j<=$to2 ;$j++) { 
            $res = grep(/$i/, @result); 
            if ($i==$j && $res == 0) { 
              print "$i enter code here\n"; 
              push(@result, $i); 
            } 
          } 
        } 
      } 
    } 
+0

thanx,它的工作 – swapnil90

+0

我有1更多數組arr2 =(4,5,2)現在我想打印$ i值只有當arr2> 3的元素。你的上面的代碼是給出輸出-3,4,5, 6,7,9,10,11,12,14,15但在實施這個新的條件後,應該給出3,4,5,6,7,9,10的輸出。我沒有得到在哪裏實施的條件,我曾嘗試過,但它沒有給出預期的結果。 @ProfGhost – swapnil90