in reply to Hash assignments using map

I ran the code on my box, Windows XP with Activestate Perl 5.8.8 and I did not get that error.
#!/usr/bin/perl -w use strict; use Data::Dump qw(dump); my @keys = qw{ a b c d }; my %hash = map { $_++ } @keys; warn "Dump " . dump( %hash ) . "\n";
#!/usr/bin/perl -w use strict; use Data::Dump qw(dump); my @keys = qw{ a b c d }; my %hash = (); for (@keys) { $hash{$_}++; } warn "Dump " . dump( %hash ) . "\n";
what I did get was,
Dump ("c", "d", "a", "b") # first script Dump ("a", 1, "c", 1, "b", 1, "d", 1) # second script

Neither answer seems to be exactly what you would I want, I think.

How about telling us what you are trying to do and see if we can address that issue?

Replies are listed 'Best First'.
Re^2: Hash assignments using map
by njcodewarrior (Pilgrim) on Feb 24, 2007 at 18:32 UTC

    I've got a HoH data structure for which I'm looking to keep only certain entries. The entries I'm looking for are contained in a list and I'd like to eliminate the entries which are not contained in that list ( I've substituted a straight hash in place of my HoH for simplicity's sake):

    #! /usr/bin/perl use strict; use warnings; use Data::Dumper; # Data Structure my %h = ( 'a' => 'z', 'b' => 'y', 'c' => 'x', 'd' => 'w', ); my @to_keep = qw{ a c }; my %keepers = map { $_ => 1 } @to_keep; foreach ( keys %h ) { if ( !exists $keepers{$_} ) { delete $h{$_}; } } $Data::Dumper::Varname = 'h'; print Dumper( \%h ); $h1 = { 'c' => 'x', 'a' => 'z' };

    I'm creating the %keepers hash out of the items in @to_keep to compare against all of the keys in %h. Since I can create the hash this way:

    my @to_keep = qw{ a c }; my %keepers; foreach ( @to_keep ) { $keepers{$_}++; } $Data::Dumper::Varname = 'keepers'; print Dumper( \%keepers ); keepers1 = { 'c' => 1, 'a' => 1 };

    I thought I could do the same thing using map:

    my @to_keep = qw{ a c }; my %keepers; %keepers = map { $_++ } @to_keep; $Data::Dumper::Varname = 'keepers'; print Dumper( \%keepers ); $keepers1 = { 'a' => 'c' };

    But it doesn't seem to work.

    njcodewarrior

      my @to_keep = qw{ a c }; my %keepers; foreach ( @to_keep ) { $keepers{$_}++; }
      ... I thought I could do the same thing using map ...

      The way to do that with map would be like this:

      my %keepers = map { $_ => 1 } @to_keep;

      The point is that, in this case, you want each iteration in map to return a key/value pair, not just a single value, and the "fat comma" (=>) does that for you.