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

Hi Monks;
Trying to match a value coming from a form to a variable:
$name = $in{'name'};
It has a value of: A C Test
When I got the value of "A C Test" I am trying to use regular expressions to add an "&" to the name, like
if($name=~s/\bA C Test\b/A&C Test/){print "<b>$name</b>"; It doesn't work, any ideas? But if I do a testing variable with a value assigned like:
$test2="A C Test";
It will work, the regular expression will validate it and it will do the substitution no problem, why is it not doing when getting the value from $name?
Thanks

Replies are listed 'Best First'.
Re: Regular Expression Problem
by pbeckingham (Parson) on Mar 29, 2004 at 14:14 UTC

    I believe you will need &amp; instead of &, if my assumption that your string is an HTML fragment is correct.

Re: Regular Expression Problem
by skx (Parson) on Mar 29, 2004 at 14:17 UTC

    Your code looks correct, although as the other reply suggests if you wish to have an ampersand displayed in a browser you should probably use the '&amp;' entity.

    Have you verified that your form input contains what you think it does? For example no trailing whitespace, etc?

    Steve
    ---
    steve.org.uk
      The problem isn't where I want to print the "&" or not but where the string matchs. See the ex;
      If you do this:
      my $test = "A C Test"; if($test=~s/\bA C Test\b/A&C Test/){print "<b>$test</b>";}

      It will work. But if the value is coming from something like this:
      my $test_name = $in{'test_name'};
      It will nor work.
      That's my problem! Tks...

        This is why I said "Have you verified that your text contains what you think it does?".

        Print it out and see!

        In the code you give above, for example, you're testing against $test - but getting the input into $test_name - which isn't being used!

        Steve
        ---
        steve.org.uk
        Have you tried using chomp to remove any trailing newlines? e.g. my $string = chomp($myinput);
Re: Regular Expression Problem
by Happy-the-monk (Canon) on Mar 29, 2004 at 14:15 UTC

    & is a metacharacter on the substitution side of a s/// which must be escaped with a backslash, like this: \&

    see perldoc perlre for more.

    Edit:
    Following my own advice, I tell you not to believe my first sentence. That would be true for the sed command, but not necessarily for Perl. In some circumstances however, when you use the /e modifier, it yields true again.

    Cheers, Sören