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

In this case, it became necessary to replace the spaces with underscores, in the Keys of a hash.

Originally posted as a Categorized Question.

  • Comment on How do I modify the KEYS in a hash (copy)

Replies are listed 'Best First'.
Re: How do I modify the KEYS in a hash (copy)
by NetWallah (Canon) on Jul 21, 2004 at 20:34 UTC
    The answers above are broken .. Awaiting cleanup. Will post correct code..

    Originally posted as a Categorized Answer.

Re: How do I modify the KEYS in a hash (copy)
by NetWallah (Canon) on Jul 21, 2004 at 17:03 UTC
    To modify keys of a hash, it is necessary to copy it. The keys can be modified in the process of the copy by using 'map' like this:
    my %HashCopy = map {tr/ /_/? $_:$_ => $OrigHash{$_}} keys %OrigHash; # Above line copies %OrigHash and Replaces Spaces with Underscore +in hash Key
    Since the 'tr' function returns the number of translations, and we do not need that number, it is essentially discarded, using the ternary "?" operator. The KEY we need is contained in "$_", with is returned under both TRUE and FALSE conditions of the "?" operator. "$_" contains the translated KEY we need.

    The VALUE is obtained simply by indexing %OrigHash.

    If anyone has an insight into the inner workings of "map" - specificaly, how does it know whether to use the translated or untranslated version of "$_" when interpreting "=> $OrigHash{$_}", please post that info here. The bottom line is that it DOES work using the original $_, not the translated one, but WHY ? Is the right-side of the "=>" evaluated first ?

    Originally posted as a Categorized Answer.

Re: How do I modify the KEYS in a hash (copy)
by NetWallah (Canon) on Jul 21, 2004 at 16:48 UTC
    To modify keys of a hash, it is necessary to copy it. The keys can be modified in the process of the copy by using 'map' like this:
    my %HashCopy = map {tr/ /_/? $_:$_ => $OrigHash{$_}} keys %OrigHash; # Above line copies %OrigHash and Replaces Spaces with Underscore +in hash Key
    Since the 'tr' function returns the number of translations, and we do not need that number, it is essentially discarded, using the ternary "?" operator. The KEY we need is contained in "$_", with is returned under both TRUE and FALSE conditions of the "?" operator. "$_" contains the translated KEY we need.

    The VALUE is obtained simply by indexing %OrigHash.

    If anyone has an insight into the inner workings of "map" - specificaly, how does it know whether to use the translated or untranslated version of "$_" when interpreting "=> $OrigHash{$_}", please post that info here. The bottom line is that it DOES work using the original $_, not the translated one, but WHY ? Is the right-side of the "=>" evaluated first ?

    Originally posted as a Categorized Answer.