PDA

View Full Version : How to replace an ampersand in Perl?


RickMC
08-16-2007, 09:38 AM
I have a text field that contains an ampersand (i.e. Bldg & Grounds). I'm trying to have the ampersand appear in a browser, but it leaves a blank space (Bldg Grounds).

I've tried $field =~ s/&/&/g; and $field =~ s/\&/&/g;, with no success.

I've even put in $field =~ s/Bldg/Test/g; just to make sure I'm referring to the correct field, etc. Bldg is replaced with Test.

Any suggestions?

KevinADC
08-16-2007, 10:51 AM
your code should work:

$field = "hi & bye & too-da-loo";
$field =~ s/&/&/g;
print $field;

prints:

hi & bye & too-da-loo

so something else is going on with yur code if it does not work.

FishMonger
08-16-2007, 04:24 PM
I think it's better to let the CGI module do the work for you, especially if there are multiple special chars that need to be escaped.
use CGI ':standard';

my $field = "hi & bye you <too-da-loo>";
$field = escapeHTML($field);
print $field;
Outputs
hi &amp; bye you &lt;too-da-loo&gt;

EDIT:
It should be obvious but you don't need to reassign the var, you can just print it.
my $field = "hi & bye you <too-da-loo>";
print escapeHTML($field);

KevinADC
08-16-2007, 08:34 PM
I think it's better to let the CGI module do the work for you

I agree.