2009年3月7日星期六

[PerlChina] Re: 有关散列的键不能使用正则表达式的问题

yes,  seems it is impossible to change the key

without adding new keys ,  so a new hash

is necessary ,  because the key of hash is used to

point to a value , so if the key changed ,  one must

tell the hash again the key has changed, and point to

the same value




use strict ;
use Data::Dumper ;

my %hash = map { $_ => 1 } 'a'..'e' ;

my %hash2 ;

for my $var ( keys %hash ) {
    my $old = $hash { $var } ;
    $var =~ s/^/sfsfs/;
    $hash2{ $var } =   $old ;
}

print Dumper  \%hash ;

print "\n\n";

print Dumper  \%hash2 ;



2009/3/7 Lee Duhem <lee.duhem@gmail.com>
2009/3/7 Leeo <yeli210@163.com>:
> 我想通过正则表达式S///来去除散列键中开头的空格,具体方法如下:
>
> foreach (keys %hash_name){
>      s/^\s+//g;
>   }
>
> print keys %hash_name;
>

你可以这么做:

while (my ($key, $val) = each %hash_name) {
   (my $k = $key) =~ s/^\s+//g;
   $new_hash{$k} = $val;
}

delete %hash_name;

反正即使在 %hash_name 中修改,改了 key 之后也是要在 hash 中增加新项的,
干脆用个新的 hash.

lee





--
           Yours Sincerely
                   Zeng Hong

--~--~---------~--~----~------------~-------~--~----~
您收到此信息是由于您订阅了 Google 论坛"PerlChina Mongers 讨论组"论坛。
 要在此论坛发帖,请发电子邮件到 perlchina@googlegroups.com
 要退订此论坛,请发邮件至 perlchina+unsubscribe@googlegroups.com
 更多选项,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问该论坛

-~----------~----~----~----~------~----~------~--~---

没有评论: