On Jul 7, 4:32 am, chas.ow...@gmail.com ("Chas. Owens") wrote: > On Wed, Jul 7, 2010 at 06:57, Srinivasa Chaitanya > T<tschaitanya....@gmail.com> wrote: > > Thanks that solves the my question. Also I want a write function similar to > > "map" for hash. > > I can use map itself for that, but I have to refer the hash variable name in > > code block. > > How I write without referring the variable? > > > my %as; > > my %bs; > > > $as {'one'} = 1; > > $as {'two'} = 2; > > $as {'three'} = 3; > > $as {'four'} = 4; > > %bs = map {$_ => ($as{$_} + 10)} keys %as; > > snip > > You could write a function (see below) that looked like this: > > my %bs = hash_map sub { shift() => shift() + 10 }, %as; > > But if all you want to do is modify the values of a hash, just say > > $_ += 10 for values %as; > > If you do not want to not modify %as, then say > > my %bs = %as; > $_ += 10 for values %bs; > > But be forewarned, that only creates a shallow copy of %as. If %as is > a nested data structure, you will need to use some form of deep > copying function like the [Storable][1] module's dclone to get a copy > that will not interact with %as. > > #!/usr/bin/perl > > use strict; > use warnings; > > sub hash_map { > my ($func, %hash) = @_; > > my %ret; > while (my ($k, $v) = each %hash) { > my %subhash = $func->($k, $v); > while (my ($k, $v) = each %subhash) { > $ret{$k} = $v; > } > } > return %ret; > > }
Or, since a humble array can be magically transformed to a hash, you could simplify slightly to: sub hash_map { my ($func, %hash) = @_; my @ret; # destined for hash-ification while (my ($k, $v) = each %hash) { push @ret, $func->($k,$v); } return @ret; } > > my %as = (a => 1, b => 2, c => 3); > my %bs = hash_map sub { $_[0] => $_[1] + 10 }, %as; > use Data::Dumper; > print Dumper \%as, \%bs; -- Charles DeRykus -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/