2016-10-13 82 views
0

我使用proc_open管道一些文本到perl腳本進行更快的處理。該文本包含url編碼的字符串以及字面空格。當一個URL編碼的空間出現在原始文本中時,它在到達perl腳本時似乎被解碼爲一個文字空間。在perl腳本中,我依賴於文字空間的位置,所以這些不需要的空間會混淆我的輸出。php - 管道輸入到perl進程自動解碼url編碼的字符串

這是怎麼發生的,有沒有辦法阻止它發生?

相關的代碼片段:

$descriptorspec = array(
    0 => array("pipe", "r"), 
    1 => array("pipe", "w"), 
); 
$cmd = "perl script.pl"; 
$process = proc_open($cmd, $descriptorspec, $pipes); 
$output = ""; 

if (is_resource($process)) { 
    fwrite($pipes[0], $raw_string); 
    fclose($pipes[0]); 
    while (!feof($pipes[1])) { 
     $output .= fgets($pipes[1]); 
    } 
    fclose($pipes[1]); 
    proc_close($process); 
} 

和原始文本輸入的行看起來是這樣的:

key url\tvalue1\tvalue2\tvalue3 

我也許可以通過轉換我輸入的格式,以避免這個問題,但由於各種原因,這是不可取的,並繞過而不是解決,關鍵問題。

此外,我知道問題發生在php腳本和perl腳本之間,因爲在將它寫入perl腳本STDIN管道之前,我已經檢查了原始文本(使用echo),並且測試了我的perl腳本直接使用url編碼的原始字符串。

我已經在下面添加了perl腳本。它基本上歸結爲一個迷你地圖減少工作。

use strict; 

my %rows; 
while(<STDIN>) { 
    chomp; 
    my @line = split(/\t/); 
    my $key = $line[0]; 
    if (defined @rows{$key}) { 
     for my $i (1..$#line) { 
      $rows{$key}->[$i-1] += $line[$i]; 
     } 
    } else { 
     my @new_row; 
     for my $i (1..$#line) { 
      push(@new_row, $line[$i]); 
     } 
     $rows{$key} = [ @new_row ]; 
    } 
} 

my %newrows; 
for my $key (keys %rows) { 
    my @temparray = split(/ /, $key); 
    pop(@temparray); 
    my $newkey = join(" ", @temparray); 
    if (defined @newrows{$newkey}) { 
     for my $i (0..$#{ $rows{$key}}) { 
      $newrows{$newkey}->[$i] += $rows{$key}->[$i] > 0 ? 1 : 0; 
     } 
    } else { 
     my @new_row; 
     for my $i (0..$#{ $rows{$key}}) { 
      push(@new_row, $rows{$key}->[$i] > 0 ? 1 : 0); 
     } 
     $newrows{$newkey} = [ @new_row ]; 
    } 
} 

for my $key (keys %newrows) { 
    print "$key\t", join("\t", @{ $newrows{$key} }), "\n"; 
} 
+0

'fwrite'調用之前'echo($ raw_string)'看看它說了什麼 – mob

+0

我已經完成了,就像我在上一段中提到的那樣。雖然謝謝!我會更加清楚的是,我在寫作之前立即檢查了原始字符串。 – Cyan

+0

perl腳本是做什麼的?你能展示它如何讀取輸入數據嗎? – xxfelixxx

回答

0

注意自我:總是檢查你的假設。事實證明,在我的數億行輸入中的某個地方,實際上是字面空格,其中應該有url編碼的空格。花了一段時間才找到它們,因爲有數億個正確的字面空間,但它們在那裏。

對不起!