What's wrong with this code ?

C

codefixer

Hi,

I am trying to do substitution for XML characters. I am getting the
following error for this piece of code.

Thanks.

sub parseXML
{
my $ret= $_;
switch ($_)
{
case "&" { print "&"; }
case "<" { print "<"; }
case ">" { print ">"; }
case "\'" { print "'"; }
case "\"" { print """; }


}


return $ret;

}
String found where operator expected at generateXML.pl line 107, near
"case "&""

(Do you need to predeclare case?)
String found where operator expected at generateXML.pl line 108, near
"case "<""

(Do you need to predeclare case?)
syntax error at generateXML.pl line 106, near ")
{"
syntax error at generateXML.pl line 108, near "case "<""
generateXML.pl had compilation errors.
 
T

Tony Curtis

On 9 Apr 2005 12:19:10 -0700,
Hi, I am trying to do substitution for XML characters. I am
getting the following error for this piece of code.

switch ($_)

Have you

use Switch;

'ed? There's no built-in switch statement.

There are also modules to do entity encoding, e.g.

HTML::Entities

but I'll let someone else narrow in on that for XML
specifically.

hth
t
 
A

Anno Siegel

Hi,

I am trying to do substitution for XML characters. I am getting the
following error for this piece of code.

Thanks.

sub parseXML
{
my $ret= $_;
switch ($_)
{
case "&" { print "&"; }
case "<" { print "<"; }
case ">" { print ">"; }
case "\'" { print "'"; }
case "\"" { print """; }


}


return $ret;

}
String found where operator expected at generateXML.pl line 107, near
"case "&""

Tony Curtis has explained how to make the case-statement work, but in
Perl "case" is rarely needed (that's why it doesn't have it in the first
place). The routine parseXML (a rather pretentious name for a modest
routine, I'd say) would be better written like this (untested):

{
my %trans = map { $_ => sprintf '&#%02d;', ord $_ } qw( & < > ' ");
sub parseXML {
print $trans{ $_} if $trans{ $_};
$_;
}
}

This uses a hash (%trans) to distinguish the cases. A bare block is used
to give %trans a small lexical scope. It doesn't hard-code the ASCII
equivalents but lets Perl do the work, though the wisdom of this could be
debated. It should work like the original, but is much more compact.

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top