Question

I have a file that contains:

foo1 = 1

foo2 =  2

foo3 =    8

.
.
.

I need to replace only the values (1,2,8...) in that file with part of a memory hash values, the ones with the same keys (foo1 -> 33,foo2 -> 44,foo3...) How can I change it using the "s///" operator? If there is other elegant ways to conduct it I'll be happy to know.

Thanks for any help,

Yohad.

Was it helpful?

Solution

one way

%hash = ("foo1"=>33,"foo2" => 44,"foo3"=>99);
while (<>){
  chomp;
  ( $one , $two ) = split /\s+=\s+/, $_;
  print "$one = $hash{$one} \n"
}

OTHER TIPS

my %new_values = ( foo1 => 33, ... );
$data =~ s{^(?<key>\w+) = \K(?<old_value>.+)$}
          {$new_values{$+{key}}}gem;

The key is the "e" flag which lets you run code to determine the replacement. The (?<...>) syntax increases readability, and the \K allows us to match the entire line but only replace the value area. The "g" flag repeats the substitution as many times as possible, and the "m" flag makes ^...$ match a line instead of the entire string. (The g and m will probably be unnecessary if you split the lines before application of the regexp.)

Here's one

%h = ("foo1"=>3, "foo2"=>5);
while (<>)
{
    #Substitute value according to expression on right hand side
    s/(\w+) = .*/$1 . " = ". $h{$1}/e;
    print;
}

s/regexPattern/replacementPattern/flags

"I am a string!"

s/\sam/'s/g

"I's a string!"

http://gnosis.cx/publish/programming/regular_expressions.html

I really can't understand what you're doing based on the descriptoin. Can you provide sample input and output?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top