1

我有一个名为%coins. 如果散列的键与某个字符串匹配,我将尝试修改散列的值。我尝试了以下代码,但无法成功。它正在创建新密钥,而不是修改现有密钥的值。

请帮忙

#!/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;
4

2 回答 2

3

单程:

#!/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(.*)/);
}
于 2013-01-21T09:24:44.487 回答
2

首先,改变

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

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

至于价值,你想

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

或者

$coins{$_} = $_ =~ s/mno/new_value/gr;    # Perl 5.14+
于 2013-01-21T11:03:24.267 回答