什么是插入多行替换字符串并将其应用于单个数组值的正确语法?

时间:2015-01-11 02:48:47

标签: perl

以下是该方案 - 该过程的一个步骤涉及在数据明显拼写错误时修复城市名称,以及一些基本转换,如“MTN”到“Mountain”等等。我已经构建了一个包含几个替换字符串的变量,并且我试图在稍后的一行输入字段中应用该组sub。

my $citysub = <<'EOF'; 
s/DEQUEEN/DE QUEEN/; 
s/ELDORADO/EL DORADO/; 
...                # there are about 100 such substitution strings 
EOF 
... 
while ($line <INFILE>) 
{ 
... 
@field = split(/","/,$line);                # it's a comma-delimited file with quoted strings; this is spltting exactly like I intend; at the end, I'll piece it back together properly 
... 
# the 9th field and 12th field are city names, i.e., $field[8] and $field[12] 
$field[8] =~ $citysub;        # this is what I'm wanting to do, but it doesn't work! 
# since that doesn't work, I'm using the following, but it's much slower, obviiously 
$field[8] = `echo $field[8]|sed -e "$citysub"`;        # external calls to system commands 

那么,插入多行替换字符串并将其应用于单个数组值的正确语法是什么?

1 个答案:

答案 0 :(得分:-1)

my %citysub = ( "DEQUEEN" => "DE QUEEN", "ELDORADO" => "EL DORADO" );
for my $find ( keys %citysub ) {
    my $replace = $citysub{ $find };
    $field[8] =~ s/$find/$replace/g;
}

说明:创建一个&#34;的东西来匹配&#34; =&GT; &#34;用&#34;替换的东西。然后循环遍历该哈希,运行s ///,匹配的东西和要替换的东西。