Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Creating a hash with key generated by a sub?

by steves (Curate)
on Nov 12, 2004 at 13:11 UTC ( #407346=note: print w/ replies, xml ) Need Help??


in reply to Creating a hash with key generated by a sub?

You had a few simple errors. This works:

use Digest::MD5 qw(md5_hex); use strict; use warnings; my $secret = "applepie"; sub get_md5 { md5_hex("$secret" . "$_[0]") }; my @array = qw(foo bar baz); my %md5_hash_broken = (map {&get_md5($_) => $_} @array); my %md5_hash = ( &get_md5('foo') => "foo", &get_md5('bar') => "bar", &get_md5('fubar') => "baz", ); my ($x, $y); while (($x, $y) = each %md5_hash) { print "$x => $y\n"; }

The errors (see my changes):

  • I got a warning on the use of $_ in get_md5();
  • Your map was not passing an argument to get_md5();
  • Your hash called get_md5() with the argument bar twice.


Comment on Re: Creating a hash with key generated by a sub?
Download Code
Replies are listed 'Best First'.
Re^2: Creating a hash with key generated by a sub?
by smullis (Pilgrim) on Nov 12, 2004 at 13:21 UTC

    Thanks for this steves...

    One point of interest - I thought that $_ was implicitly passed to map?
    The %blah = (map {&get_md5, $_} @array); worked for me fine...

    Cheers,

    SM

      I should clarify: In other places, get_md5() is passed with one argument, which I assumed you wanted concatenated to $secret to make the key. The way map was originally set up, it was not passing anything to get_md5() -- it was calling it with no arguments and using $_ as the hash value. Unless I'm missing something ...

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2015-07-08 01:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls