1

I have a hash named %coins. I am to trying to modify the value of the hash if the key of the hash matches with some string. I tried the following code, but couldn't succeed. It is creating new key instead of modifying the existing key's value.

Please help

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my %coins;
%coins = ( "abc" , 1,
          "mno pqr" , 2,
          "xyz",  3 );

print Dumper \%coins;

if(grep {/mno/} keys %coins)
{
    print"matched \n";
    $coins{$_} = s/$coins{$_}/new_val/g;
}

print Dumper \%coins;
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
SS Hegde
  • 729
  • 2
  • 14
  • 33

2 Answers2

3

One way:

#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper;

my %coins;
%coins = ( "abc" , 1,
          "mno pqr" , 2,
          "xyz",  3 );

print Dumper \%coins;

my $newval=9;
foreach my $k (keys%coins){
        $coins{$k}=$1.$newval.$2 if ($k =~/(.*)mno(.*)/);
}
Guru
  • 16,456
  • 2
  • 33
  • 46
  • Thanks for the answer. But I wanted to replace the value of `mno pqr` (i.e 2) with `9 pqr`. – SS Hegde Jan 21 '13 at 09:43
  • OK. To make it clear: I want to replace the value of the matched key with the value same as the key but by replacing matched content in key. Pheww.. its getting more confused.. For example (in the above code): If the matched key is "mno pqr" then I want to have the value of "mno pqr" as "new_value pqr". – SS Hegde Jan 21 '13 at 10:03
  • What if the key is `ghi mno pqr`? The value after modification will be `9 pqr`. It should have been `ghi 9 pqr`..... – SS Hegde Jan 21 '13 at 10:16
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/23083/discussion-between-guru-and-ss-hegde) – Guru Jan 21 '13 at 10:43
2

For starters, change

if(grep {/mno/} keys %coins)
{
    ...
}

to

for(grep {/mno/} keys %coins)
{
    ...
}

As for the value, you want to

( my $new_val = $_ ) =~ s/mno/new_value/g;
$coins{$_} = $new_val;

or

$coins{$_} = $_ =~ s/mno/new_value/gr;    # Perl 5.14+
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • If I do so, the output is `$VAR1 = { 'mno pqr' => 2, 'abc' => 1, 'xyz' => 3 }; matched $VAR1 = { 'mno pqr' => '', 'abc' => 1, 'xyz' => 3 }; ` But after replacing, It should have been `'mno pqr' => new_value pqr` – SS Hegde Jan 21 '13 at 11:16
  • The value is completed replaced as `new_val`. Where as it should have been `new_val pqr` – SS Hegde Jan 21 '13 at 11:29
  • For example (in the above code): If the matched key is "mno pqr" then I want to have the value of "mno pqr" as "new_value pqr" – SS Hegde Jan 21 '13 at 11:29
  • wow, that's a weird thing to do. Fixed that bug too. Guru's answer is not as bad as I thought it was. (It just doesn't handle multiple instances of "mno", which may or may not be a problem.) – ikegami Jan 21 '13 at 11:37
  • Thanks for the answer. That fixes handling of multiple instances of "mno". – SS Hegde Jan 21 '13 at 11:50