in reply to Trimming whitespaces methods

Instead of capturing and replacing all with the captured string, I'd just remove whitespace at the beginning and end of the string:

s/^\s+|\s+$//g;

one way to trim keys and values of a hash:

%hash = map { $v = $hash{$_}; s/^\s+|\s+$//g for $v,$_; $_,$v } keys % +hash; # another way which doesn't copy the entire has, just the keys for my $key (keys %hash) { my $value = delete $hash{$key}; for ($key, $value) { s/^\s+|\s+$//g; } $hash{$key} = $value; }

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Replies are listed 'Best First'.
Re^2: Trimming whitespaces methods
by wfsp (Abbot) on Jun 30, 2008 at 14:41 UTC
    I think tinkering with keys should come with a health warning: "If you didn't have duplicate keys before are you really sure you won't after you've tinkered with them?".

    It's an edge case for sure but you can't rule out having " keyone" and "keyone". If you suspect there is leading and trailing space on your keys (and hence the question) it becomes less of an edge case. You'll have lost data and not noticed.

    It must be better to do your trimming (keys and values) while building the hash, not after (you can use exists to catch any resulting dupes). If that's not possible/feasable I'd go for creating a hash of arrays and go through and count the little blighters.

    Did I mention I've been bitten so often by stray whitespace (it's everywhere!) that I've become a tad obsessive? :-)