2011-09-10 39 views
0

我的問題:remove元素加入數組結果

@array = (possible text, 
      text surrounded with round brackets, 
      text without brackets, 
      text surrounded with round brackets, 
      possible text); 

$line = join(' ', @array); 

我想刪除,如果在第一支架之前的任何文字和加入結果(可能的文本)的最後括號後的任何文本。 謝謝。

真正的代碼:

my (@lines, $line, $anchor, $left, $right, $parent, $elem); 
($anchor) = $tree->look_down(_tag=>"span", class=>"txt"); 
if ($anchor) { 
    $elem = $anchor; 
    my ($product, @tmp); 
    while (($elem = $elem->right()) && 
      ((ref $elem) && ($elem->tag() ne "table"))) { 
     @tmp = get_all_text($elem); 
     push @lines, @tmp; 
     $line = join(' ', @tmp); 
+3

請張貼真實密碼? – 2011-09-10 12:24:22

+3

同等重要:後期示例輸入數據和期望的輸出。 – FMc

回答

0

看看這對你的作品:

$line =~ s/.*?(\(.*\)).*/$1/; 
0

您的代碼有語法錯誤。

你應該先解決這個問題,然後弄清楚如何進一步處理$ line。

也許你忘了將任務分配給@array a qw?

如果是這樣,那麼下面的代碼會在第一個「文本包圍」 和上一個「文本包圍」之後的文本之前切出文本。

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

@array = qw(possible text, 
      text surrounded with round brackets, 
      text without brackets, 
      text surrounded with round brackets, 
      possible text); 

$line = join(' ', @array); 

$line =~ s/.*?(text surrounded with round brackets)/$1/; 
$line =~ s/(.*text surrounded with round brackets).*/$1/; 
print "$line\n"; 
0

嘗試:

$line =~ s/\A[^(]+//; 
$line =~ s/[^)]+\z//; 
0

你可以循環數組,建立在那裏你看到的第一架和最後一個支架的價格指數比,然後提取對應的片。

my @array = ('possible text', 
    '(text surrounded with round brackets)', 
    'text without brackets', 
    '(text surrounded with round brackets)', 
    'possible text'); 

my ($first, $last); 
for (my $i = 0; $i < $#array; ++$i) { 
    next unless $array[$i] =~ m/^\s*\(/; # maybe adapt this regex 
    $first = $i; 
    last; 
} 
for (my $j = $#array; $j > 0; --$j) { 
    next unless $array[$i] =~ m/^\s*\(/; # tweak this too then 
    $last = $j; 
    last; 
} 

my $line = join (' ', @array[$first..$last]); 

mapgrep,恐怕這不是優雅。

編輯:原本有一個循環,以找到既$first$last但兩個獨立的循環更有效。這也取決於你的數據結構;如果沒有很多,這個優化顯然不是很重要。另一方面,如果真的有很多數據,你可能會進一步優化。