2010-12-06 58 views
0

如何重新編寫perl中的字符串?重新編寫perl中的字符串查詢

例如,考慮字符串「盧浮宮在哪裏?」

怎樣才能像琴絃以下幾點:

「的是盧浮宮位於」
「盧浮宮位於」
「位於盧浮宮是」

這些被用作查詢做一個網絡搜索。

我試圖做這樣的事情:

擺脫標點符號和分裂成句的話。
my @words = split //,$ _ [0];

我不需要字符串中的第一個單詞,所以擺脫它。
shift(@words);

然後我需要移動下一個單詞通過數組 - 不知道如何做到這一點!

最後將單詞數組轉換回字符串。

回答

0
my @head; 
my ($x, @tail) = @words; 
while (@tail) { 
    push @head, shift @tail; 
    print join " ", @head, $x, @tail; 
}; 

,或者就 「泡」 通過陣列$ X:$字[$ N-1]和詞語[$ n]的

foreach $n ([email protected]) { 
    ($words[$n-1, $words[$n]) = ($words[$n], $words[$n-1]); 
    print join " ", @words, "\n"; 
}; 
1

稍微更詳細的例如:

use strict; 
use warnings; 

use Data::Dumper; 


my $str = "Where is the Louvre located?"; 

# split into words and remove the punctuation 
my @words = map {s/\W+//; $_} split//, $str; 

# remove the first two words while storing the second 
my $moving = splice @words, 0 ,2; 


# generate the variations 
my @variants; 
foreach my $position (0 .. $#words) { 

    my @temp = @words; 
    splice @temp, $position, 0, $moving; 
    push @variants, \@temp; 

} 

print Dumper(\@variants);