I’m not getting the result expect from the following code:
#!/bash/perl
use strict;
use warnings;
my @file;
my $file2;
open (IN, "+</home/opmeitle/labs-perl/numbers");
@file = <IN>;
seek IN,0,0;
my %change = ( 80.928 => "85.950", 320.000 => "380.500");
my $changekey = join "|", keys %change;
foreach $file2 (@file){
$file2 =~ s/($changekey)/$change{$1}/g;
print IN $file2;}
close IN;
This is the contents of /home/opmeitle/labs-perl/numbers:
80.928
320.000
Here is the output:
85.950
380.500.000
Here is the result I desire:
85.950
380.500
I appreciate your answers.
luis.
but, looking this example, change in file numbers 80.928 and 320.000 for “Hola, mi nombre es Luis y vivo en Argentina” in code my %change = ( nombre => “name”, mi => “my”); this is result “Hola, my name es Luis y vivo en Argentina a ” in the end , an word the more! because?
Your first problem is in
.(dot).(dot) – in regular expression means “any symbol”.Your second problem in 320.000 — this is the number and it’s exactly equals to 320
320.000 =~ s/320/380.500/g; => 380.500.000
I suppose that solution may be in changing type of hash keys from numbers to strings
and escape all dots
'.' => '\.'To support my point of view, I wrote small script:
And voila, it produces output:
320|80.928But when %change hash is written as
my %change = ( "80.928" => "85.950", "320.000" => "380.500");, output would be320.000|80.928And the third problem, you open file in read-write mode, but when resulting file has less size then source, at the end would be rubbish. To avoid this, you must use
truncate, or open file in readonly mode, read it, close, and after that open it in writeonly mode.