in reply to Strip spaces in hash

If 'strip spaces' simply means to remove all spaces, here's one approach:

>perl -wMstrict -le "use Data::Dumper; my %hash = ( ' k 1 ' => ' v 1 ', ' k 2 ' => ' v 2 ', ); print Dumper \%hash; %hash = map { s{\s+}{}xmsg; $_ } %hash; print Dumper \%hash; " $VAR1 = { ' k 2 ' => ' v 2 ', ' k 1 ' => ' v 1 ' }; $VAR1 = { 'k2' => 'v2', 'k1' => 'v1' };

Beware, however, that if the original hash has a key  ' k e y ' and also another key  'key', something is going to get clobbered.

Update: Per ikegami's reply Re^2: Strip spaces in hash, I would add the cautionary note that, had the output of map not ultimately been assigned to the source hash in the code above, the values of that hash would, as a side effect, and perhaps quite unexpectedly and mysteriously, have been altered. Many happy hours of debugging ensue.

Replies are listed 'Best First'.
Re^2: Strip spaces in hash
by ikegami (Patriarch) on Dec 09, 2009 at 17:38 UTC
    You're unintentionally modifying the hash values before the assignment. True, it's harmless in this case, but I think it's a bad habit. You also have loads of useless options on your substitution.
    %hash = map { my $s=$_; $s=~s/\s+//g; $s } %hash;

    or

    use List::MoreUtils qw( apply ); %hash = apply { s/\s+//g } %hash;
      ... unintentionally modifying the hash values before the assignment [is] harmless in this case, but I think it's a bad habit.

      The modification was certainly not unintentional (or unconsidered), but I take your point. I wish I had thought to include a cautionary note about this (in fact, I think I will right now!) when I was going on about key collision, as I wish I had thought to use the  apply function.

      ... loads of useless options on your substitution.

      I have adopted this and other regex-related BPs from Conway's PBP. I know many monks would disagree, but the arguments for these practices are compelling to me.