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

Actually, substr can modify the string if you use the fourth argument.

Replies are listed 'Best First'.
Re^4: Using substr on Hash Keys
by ikegami (Patriarch) on Sep 10, 2008 at 23:38 UTC
    Yes, but hash keys aren't Perl strings, so keys actually returns a copy of the keys, so substr can only modify the copy, not the key itself.

      I was replying to jettero who said "substr doesn't actually modify the string like splice modifies arrays" and there was no mention of hash keys in his post.

      And actually, hash keys are strings, just not modifiable strings, but there is no error if you try to modify them:

      $ perl -le' use warnings; use strict; my %x = qw/abcd efgh ijkl mnop/; substr $_, 0, 2, "" for %x; print for %x; ' ijkl op abcd gh

        I was replying to jettero who said "substr doesn't actually modify the string like splice modifies arrays" and there was no mention of hash keys in his post.

        I know. I just related your answer to the topic. Out of context answers are dangerous.

        And actually, hash keys are strings

        I never said they weren't. I said they weren't Perl strings. They're not C strings either. They're C strings with a flag byte appended.

        struct hek { U32 hek_hash; /* hash of key */ I32 hek_len; /* length of hash key */ char hek_key[1]; /* variable-length hash key */ /* the hash-key is \0-terminated */ /* after the \0 there is a byte for flags, such as whether the key is UTF-8 */ }; typedef struct hek HEK;

        hash keys are strings, just not modifiable strings, but there is no error if you try to modify them:

        Not so. What you call a hash key is modifiable.

        use warnings; use strict; my %x = qw/abcd efgh ijkl mnop/; for (%x) { substr $_, 0, 2, ""; print("$_\n"); }
        kl op cd gh

        That's because it's a copy of the hash key, not the hash key itself.