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

Hi Monks!
Can anyone explain to me why this regular expression is not giving me the last print without the spaces on the name and instead it is literally printing the "\s+", why?

#!/usr/bin/perl use strict; use CGI::Carp qw(fatalsToBrowser); use CGI qw(-oldstyle_urls :standard); print header(); my $name = 'Joe Doe'; print "Name 1 = $name<br>"; #print "Joe Doe" $name=~s/\s/_/; print "Name2 = $name<br>"; #print "Joe_Doe" $name =~s/_/\s+/; print "Name 3 = $name<br>"; #print "Joes+Doe"


Thanks for the help!

Replies are listed 'Best First'.
Re: Regular Expression Help
by jwkrahn (Abbot) on Aug 23, 2006 at 17:52 UTC
    \s is a character class that represents whitespace and it is used in regular expressions. In the substitution operator the left-hand side is a regular expression and the right-hand side is a string and \s in a string is just the character 's'.
      Building on this, you probably want:
      s/_/ /g
Re: Regular Expression Help
by Fletch (Bishop) on Aug 23, 2006 at 17:50 UTC

    Because the right hand side is (baring options to the contrary) basically a double quoted string and is interpreted thusly.

Re: Regular Expression Help
by graff (Chancellor) on Aug 24, 2006 at 02:41 UTC
    $name =~s/_/\s+/;

    Well, that's a bit silly, isn't it? You should understand that "\s+" in the left (regex-match) side of the s/// operator is supposed to mean "match one or more of any kind of white space character". And the right (replacement string) side of the s/// operator is supposed to say exactly what should replace the match.

    So the reason why "\s+" can't do what you meant as part of the replacement string is: it doesn't say exactly what sort of white space character(s) -- or how many -- should replace the matched string. The same concept applies to any character-class, quantifier or grouping symbol used in a regex match: there's no way they can have the same meaning as replacement strings -- rather than being meaningless, they are simply taken "literally".

A reply falls below the community's threshold of quality. You may see it by logging in.