in reply to Re^2: Using substr on Hash Keys
in thread Using substr on Hash Keys

I was going to do something like this, but I couldn't reason out which of the delete vs the substr would happen first.

Doesn't matter, unless you expect a collision between a new key and an old key. If that's the case, other solutions have the problem too. (The solution is to use another hash.)

What does matter is that all the keys are fetched before any insertion into and deletion from the hash. And they are. for loads the entire list over which to iterate into memory before starting to loop.

Replies are listed 'Best First'.
Re^4: Using substr on Hash Keys
by jettero (Monsignor) on Sep 11, 2008 at 01:45 UTC
    I was picturing it like this (incorrectly thinking substring would modify $_), where I think the order does matter, and I can't predict what would happen:
    $hash{ do{ $_ =~ s/(..)$//; $_ } } = delete $hash{ $_ } for keys % +hash;

    What appears to happen is that the lvalue is evaluated first, so I end up deleting the modified key into the new key position (leaving all the old keys in place and defining new keys to undef); but I couldn't have guessed until I tried it, so I'd tend to lean toward a for() loop like my first post.

    And I think that was jwkrahn's point too:

    $hash{ substr $_, 1, 20, "" } = delete $hash{ $_ } for keys %hash;

    -Paul