I have a ~35MB KML file where all the placemarks are named "kml1234" and the like. I want to replace the name with a readable string like "Area 9987" and I have the lookup table. I found a snippet of perl here (https://stackoverflow.com/a/6435950) and it worked for the majority of the placemarks. However, I found that it failed in specific cases. Here is the code.
$repl{kml1} = "Area A";
$repl{kml12} = "Area B";
$repl{kml123} = "Area C";
$repl{kml69} = "Area D";
$repl{kml4458} = "Area E";
$s = <<HEADER;
\$start = time;
open(F, "input.txt");
open(OUTPUT, ">output.txt");
while (<F>) {
HEADER
foreach $key (keys %repl) {
$s .= "s/$key/$repl{$key}\/;\n"
}
$s .= <<FOOTER;
print \$_;
}
close(F);
close(OUTPUT);
print "Elapsed time (eval.pl): " . (time - \$start) . "\r\n";
FOOTER
eval $s;
I've tested this in isolation using a test string (put into input.txt):
<Placemark id="kml123">
The expected result from this is:
<Placemark id="Area C">
However, if I run the script again with the same input (kml123), I get any one of the 3 results below:
<Placemark id="Area A23">
<Placemark id="Area B3">
<Placemark id="Area C">
It seems that the subsititution is somehow truncating $key to only kml1 or kml12 sometimes? I notice that I never get "Area D" or "Area E" which is expected, and I suspect that it is because they do are not similar enough to kml123, just the first 3. Any clues?
Main problem was mentioned already in @ahjohnston25's answer, but you took over so ugly code with evaling and fuzzy stuff, so I made it a bit simpler and cleaner:
#!/usr/bin/perl
use strict; use warnings; use autodie;
my %repl = (
"kml1" => "Area A",
"kml12" => "Area B",
"kml123" => "Area C",
"kml69" => "Area D",
"kml4458" => "Area E",
);
open( my $F, '<', "input.txt" );
open( my $OUTPUT, '>', "output.txt" );
while ( <$F> ) {
foreach my $key ( sort keys %repl ) {
s/\b$key\b/$repl{$key}/g;
}
print $OUTPUT $_;
}
close( $F );
close( $OUTPUT );
I hope in this form it is much easier to understand what is going on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With