Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^3: Hash assignments using map

by mk. (Friar)
on Feb 24, 2007 at 16:42 UTC ( #601891=note: print w/replies, xml ) Need Help??


in reply to Re^2: Hash assignments using map
in thread Hash assignments using map

the first statement takes the elements from the array @keys, increments them and adds to the hash %hash.
first point is, you only have letters, no numbers, so Perl won't "increment" them, and will just add them as they already are to the hash.
secont point, the hash takes two elements to populate a key-value pair. for example, a hash %h = (a => 1, b => 2, c => 3) could also be written as %h = qw{a 1 b 2 c 3}.
the second statement takes each element from the array as a key of the hash, incrementing its value each time it's processed (which means if you have twice the element "a" in the array, the value of the key "a" in the hash will be 2 etc). if you want to use map to do that, it'd like map { $hash{$_}++ } @keys.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*women.pm

Replies are listed 'Best First'.
Re^4: Hash assignments using map
by chargrill (Parson) on Feb 24, 2007 at 16:47 UTC
    first point is, you only have letters, no numbers, so Perl won't "increment" them

    Really?

    $ perl -le '$c = "a"; print ++$c' b

    Check perlop:

    The auto-increment operator has a little extra builtin magic to it. ... If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern "/^[a-zA-Z]*[0-9]*\z/", the increment is done as a string, preserving each character within its range, with carry ...

    Update: Though you're actually right, but only by coincidence. Using the postfix autoincrement won't make the hash elements incremented.

    $ perl -Mstrict -MData::Dumper -we 'my @a = qw(a b c d); \ my %h = map { $_++ } @a; print Dumper \%h' $VAR1 = { 'c' => 'd', 'a' => 'b' };


    --chargrill
    s**lil*; $*=join'',sort split q**; s;.*;grr; &&s+(.(.)).+$2$1+; $; = qq-$_-;s,.*,ahc,;$,.=chop for split q,,,reverse;print for($,,$;,$*,$/)
      my bad!
      it actually increments the elements of the array, but adds them unchanged to the hash.
      thanks for pointing that out, chargrill++! :)

      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      *women.pm

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://601891]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2022-01-22 00:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (60 votes). Check out past polls.

    Notices?