Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: How to convert hash keys to utf8

by hexcoder (Deacon)
on Sep 23, 2021 at 09:35 UTC ( #11136963=note: print w/replies, xml ) Need Help??


in reply to How to convert hash keys to utf8

I interpret your question as "how do i change the hash key in a hash?"

If you can change the original hash, I suggest this code snippet, which deletes entries with the non-utf8 keys and reuses the values for the utf8-version key.

for (keys %oldhash) { # change key and keep the value $oldhash{utf8_on($_)} = delete $oldhash{$_}; } call_pyfunc(\%oldhash);

Replies are listed 'Best First'.
Re^2: How to convert hash keys to utf8
by soonix (Canon) on Sep 24, 2021 at 08:51 UTC
    Neither _utf8_on (in Encode.pm) nor utf8_on (in DSU) mention a return value, _utf8_on (in DSU, probably different from Encode's) explicitly says
    The data structure is converted in-place and as a convenience the passed variable is returned from the function.
    Given mpersico's observation, it looks like for the hash itself it is not relevant whether its keys have an utf8 flag set or not.
Re^2: How to convert hash keys to utf8
by mpersico (Monk) on Sep 23, 2021 at 17:44 UTC
    Interesting point. That's not what I did though. My solution was
    $ref->{ utf8_on($key) } = $ref->{$key};
    and yet, I did not double the size of the hash, as proven by tests I have written to count and enumerate the keys as received in Python from Perl. I believe that my code "works" without duplicating the keys because utf8_on is not changing or manipulating the actual string that is the key; all it is doing is manipulating the metadata.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2021-12-09 10:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (36 votes). Check out past polls.

    Notices?