hakkr has asked for the wisdom of the Perl Monks concerning the following question:

I have decided I love map and want to use it for everything. Does map work on associative arrays (hashes). I have tried things like  map {$_=>$sth->quote($_)} %hash; to no avail do I have to translate me hash to an array or use 'keys' and 'values'. thx

Replies are listed 'Best First'.
Re: map hash instead of map array
by shotgunefx (Parson) on Apr 04, 2002 at 12:12 UTC
    map { $hash{$_} = 'whatever' } keys %hash;
    If you don't use keys on the hash, it will use hash like a list.. Giving key then value, key then value...

    -Lee

    "To be civilized is to deny one's nature."
      thanks was suffering mental blockage
Re: map hash instead of map array
by strat (Canon) on Apr 04, 2002 at 12:59 UTC
    If you just want to change the values of the hash to a new hash, you could do something like:
    my %newHash = (); @newHash{ keys %oldHash } = map { &quote($_) } values %oldHash;
    For keys and values always has to give an identical order.
    TIMTOWTDI :-)

    Best regards,
    perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

Re: map hash instead of map array
by Juerd (Abbot) on Apr 04, 2002 at 12:18 UTC

    do I have to translate me hash to an array or use 'keys' and 'values'

    Use keys or values, yes. You had the idea yourself, but apparently didn't try it. Often, you get results very fast and accurately by asking perl instead of asking Perl Monks.

    Update Here's the solution:

    $_ = $sql->quote($_) for values %hash
    Don't use map where normal loops are good enough.

    U28geW91IGNhbiBhbGwgcm90MTMgY
    W5kIHBhY2soKS4gQnV0IGRvIHlvdS
    ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
    geW91IHNlZSBpdD8gIC0tIEp1ZXJk
    

Re: map hash instead of map array
by Biker (Priest) on Apr 04, 2002 at 13:56 UTC

    "I have decided I love map and want to use it for everything."

    map() builds and returns a list. (Or, in scalar context, the number of elements in the list constructed.)

    Don't use map() unless you intend to make use of the list returned. (Or the scalar containing the number of elements.)

    Update: As Juerd points out, map() returns a list or the number of scalars in the list. Not an array as I initially stated.


    Everything went worng, just as foreseen.

      map() builds and returns an array. (Or, in scalar context, the number of elements in the array constructed.)

      s/array/list/g

      Don't use map() unless you intend to make use of the array returned.

      s/array/list/

      U28geW91IGNhbiBhbGwgcm90MTMgY
      W5kIHBhY2soKS4gQnV0IGRvIHlvdS
      ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
      geW91IHNlZSBpdD8gIC0tIEp1ZXJk