2012-06-26 15 views
2

我開始學習perl,並且正在使用正則表達式編寫簡單的冒泡排序。但是,我無法正確排序(按字母順序,用空格分隔)。它只是返回相同的字符串。有人可以幫忙嗎?我相信這件事很簡單。謝謝:使用Perl正則表達式編寫冒泡排序

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

my $document=<<EOF; 
This is the beginning of my text...#more text here; 
EOF 

my $continue = 1; 
my $swaps = 0; 
my $currentWordNumber = 0; 
while($continue) 
{ 
     $document =~ m#^(\w+\s+){$currentWordNumber}#g; 
     if($document =~ m#\G(\w+)(\s+)(\w+)#) 
     { 
       if($3 lt $1) 
       { 
         $document =~ s#\G(\w+)(\s+)(\w+)#$3$2$1#; 
         $swaps++; 
       } 
       else 
       { 
         pos($document) = 0; 
       } 
       $currentWordNumber++; 
     } 
     else 
     { 
       $continue = 0 if ($swaps == 0); 
       $swaps = 0; 
       $currentWordNumber = 0; 
     } 
} 

print $document; 

已解決:我想出了問題。我在一個字之後沒有考慮到標點​​符號。

+0

爲什麼正則表達式和冒泡排序? – nhahtdh

+0

我試圖學習perl,並在「Beginning Perl」一書中看到了一個類似的例子。我試圖複製它 – Nosrettap

+0

這聽起來像一個糟糕的主意 - 整個「正確工作的正確工具」出現了。正則表達式對匹配/識別和更改已知遵循某種模式的文本非常有用 - 因此名字。冒泡排序不是這類問題。 Perl:當然。正則表達式:不。 – lxop

回答

2

如果你只是想所有排序的話,你沒有使用正則表達式......這簡直是分裂被換行符和空格文本要快很多:

sub bsort { 
    my @x = @_; 
    for my $i (0..$#x) { 
     for my $j (0..$i) { 
      @x[$i, $j] = @x[$j, $i] if $x[$i] lt $x[$j]; 
     } 
    } 
    return @x; 
} 

print join (" ", bsort(split(/\s+/, $document)));