Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Replacing Whitespace with Underscore

by jimpudar (Pilgrim)
on Apr 09, 2018 at 16:24 UTC ( #1212598=note: print w/replies, xml ) Need Help??


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

    Thanks! It worked perfectly!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1212598]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2020-10-20 12:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (210 votes). Check out past polls.

    Notices?