in reply to Replacing Whitespace with Underscore
You should turn on 'use strict' and 'use warnings', this will help lead you to a better solution.
It seems your main problem might be that you are confusing the space character ' ' with the whitespace character class.
In a regex, '\s' matches not only the space character, but ANY whitespace character. See Whitespace.
Your substitutions like 's/\[/\s/' will fail because '\s' is only recognized as whitespace in a regex:
$ perl -wE 'my $str = "JA_PH"; $str =~ s/_/\s/; say $str' Unrecognized escape \s passed through at -e line 1. JAsPH $ perl -wE 'my $str = "JA_PH"; $str =~ s/_/ /; say $str' JA PH
Also, your regex for substituting whitespace with underscore will only match a whitespace character followed by a space character. I don't think this is quite what you meant.
$ perl -wE 'my $str = "Some text with whitespace"; $str =~ s/\s /_/g; + say $str' Some text with_whitespace $ perl -wE 'my $str = "Some text with whitespace"; $str =~ s/\s/_/g; +say $str' Some_text_with__whitespace $ perl -wE 'my $str = "Some text with whitespace"; $str =~ s/\s+/_/g; + say $str' Some_text_with_whitespace
Best,
Jim
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Replacing Whitespace with Underscore
by CPTQuesoXI (Novice) on Apr 09, 2018 at 16:48 UTC |
In Section
Seekers of Perl Wisdom