代替我有一個文件:map.txt
- 這是具有1000+線等以下格式:快速多個搜索和在Perl
aaa { 123 };
bbb { 4567 };
cc { 89 };
我有具有5條百萬+線input.txt
另一文件;
其中包含aaa爲"aaa"
,bbb爲"bbb"
格式。
我可以買到在Perl中最快速的方法來建議搜索&替換的所有發生:
"aaa"
與"123"
等"bbb"
與"4567"
。
代替我有一個文件:map.txt
- 這是具有1000+線等以下格式:快速多個搜索和在Perl
aaa { 123 };
bbb { 4567 };
cc { 89 };
我有具有5條百萬+線input.txt
另一文件;
其中包含aaa爲"aaa"
,bbb爲"bbb"
格式。
我可以買到在Perl中最快速的方法來建議搜索&替換的所有發生:
"aaa"
與"123"
等"bbb"
與"4567"
。
使用哈希。使用舊字符串作爲鍵,替換字符串作爲值。
#!/usr/bin/perl
use warnings;
use strict;
my %map;
open my $MAP, '<', 'map.txt' or die $!;
while (<$MAP>) {
my ($pattern, $replacement) = /(.*) { (.*) };/;
$map{$pattern} = $replacement;
}
open my $IN, '<', 'input.txt' or die $!;
while (<$IN>) {
s/"(.*)"/"$map{$1}"/g;
print;
}
輸出到一個新文件,修改的最後一段如下:
open my $IN, '<', 'input.txt' or die $!;
open my $OUT, '>', 'output.txt' or die $!;
while (<$IN>) {
s/"(.*?)"/exists $map{$1} ? qq{"$map{$1}"} : qq{"$1"}/ge;
print {$OUT} $_;
}
close $OUT;
第二部分在屏幕上正確打印;但我想重定向到output.txt,對我來說工作不正常。要麼獲得與'input.txt'相同的'output.txt',要麼獲得'map.txt'中未提及的那些變量的一些額外的空替換。你能否更新代碼以正確地重定向到'output.tx'? – Brijesh 2014-08-29 14:27:14
@Brijesh:你是說如果你運行'map.pl> output.txt',它不起作用? – choroba 2014-08-29 14:38:37
不是這樣,實際上我沒有試過,也不能這樣做,因爲這部分是一個大型Perl程序的一部分。我需要將本節的輸出作爲'output.txt'來進一步處理.. – Brijesh 2014-08-29 14:45:29
您應該使用trie(https://en.wikipedia.org/wiki/Trie)。
CPAN上有一個模塊:http://search.cpan.org/~avif/Tree-Trie-1.5/Trie.pm雖然實現非常簡單。
可能是這樣的:
#!/usr/bin/env perl
use strict;
use warnings;
my %hash = (
aaa => '123',
bbb => '4567',
cc => '89',
)
open FILE, '>', 'input.txt';
while(<FILE>)
{
if(/"([a-z]+)"/) {
s/"$1"/'"'.$hash{$1}.'"'/ge if($hash{$1});
}
}
''「'。$ hash { $ 1}'''''寫得更好'qq(「$ hash {$ 1}」)''。但爲什麼要使用評估,它不是一個好主意,而且不需要:'「hash {$ 1}」' – TLP 2014-08-29 11:17:29
使用哈希。非常簡單,除非你有嵌套引號。 – TLP 2014-08-29 10:04:20
另請參閱後續討論:http://stackoverflow.com/questions/25579821/perl-not-matching-multiple-hash-keys-comes-in-a-single-line – tripleee 2014-08-30 08:15:18