Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Can someone whip up a regex that will scan a hash for any and all commas and if there isn't a trailing space following the comma, it'll put one there (talking about the hash values). If there's already a space after the comma, nothing needs to happen.

Some people just don't add spaces and because of this their text breaks my table widths and distorts my page.

Replies are listed 'Best First'.
Re: regex to break on commas
by TedPride (Priest) on May 14, 2005 at 19:19 UTC
    Or just:
    s/,(?! )/, /g for values %hash;
Re: regex to break on commas
by davidrw (Prior) on May 14, 2005 at 18:36 UTC
    foreach my $k (keys %hash){ $hash{$k} =~ s/,(?! )/, /g; }
    Update: $hash{$_} =~ s/,(?! )/, /g for keys %hash;
    Update: Taking it even one more step is tedpride's nice solution below, avoiding keys altogether.
Re: regex to break on commas
by Forsaken (Friar) on May 14, 2005 at 18:31 UTC
    sub something { #takes a hashref as an argument. creates a copy of the hash, scans e +ach of the values for any occurence of a comma and if necessary, adds + a space after it. #Returns a hashref to a newly constructed, thus corrected, hash. my $hashref = shift; unless(ref($hashref) eq 'HASH') { print "argument to \'something\' must be a hash reference"; retu +rn; } my %oldhash = %{$hashref}; my %newhash; foreach my $key (keys(%oldhash)) { my $value = $oldhash{$key}; $value =~ s/,/, /g; $newhash{$key} = $value; } return \%newhash; }
    It isn't the prettiest or the most efficient, but it does the job and clearly shows how it does it.

    Disclaimer: untested code, use at your own risk.

    Update: untested indeed. that's what happens when engaging the black arts of regex without the proper sacrifice of a virgin first. the regex of the poster below me seems to work a little better ;-)

    Remember rule one...