in reply to hash key confusion

My recommendation is that you should convert that hexadecimal-value into an ASCII hexadecimal string, and use that as the hash-key.

Otherwise, you run the risk that Perl will, well, “try too hard” to interpret your hex-value as a string ... say, as a Unicode string ... and, maybe, as an ill-formed string.   (It’s never a good thing when computers “try too hard” ... heh ... especially when their “perfectly reasonable guesses” are altogether wrong for what you are trying to do.)   Therefore, remove all need to ask the computer to guess.   Just convert the hexadecimal data into a byte-by-byte representation in nice, 1970’s ASCII, and use that as the key.   Suddenly, the entire situation is “unambiguous.”   Perfect.

Replies are listed 'Best First'.
Re^2: hash key confusion
by davido (Cardinal) on Mar 24, 2014 at 21:31 UTC

    Which is better?

    # This? if( exists $hash{ sprintf "%#x", ord('a') } ) { ... } # or this? if( exists $hash{a} ) { ... }

    I'd say that we don't know enough about his needs to make the determination that he ought to be storing stringified hexadecimal values as hash keys. There may be specific cases where that's useful, but in the general case it smells bad to me.

    It almost seems like he's trying to create a hash that crossreferences hex values with literal characters. That's working too hard, when chr, ord, and sprintf already have the conversions down pat.


    Dave

      In making my recommendation, I don’t / didn’t know that there was any sort of “intrinsic meaning” in the keys that the OP intends to store.   If the true target of his intentions is, indeed, characters, versus the hex/binary representations of the same, then obviously a blind binary-to-hex conversion would not be sufficient for his/her purposes.   (In which case, “good catch.”)