You are viewing a plain text version of this content. The canonical link for it is here.
Posted to modperl@perl.apache.org by Philip Mak <pm...@aaanime.net> on 2001/04/29 10:34:40 UTC
[OT] How to write this perl sub w/o variables?
Is it possible to rewrite this perl subroutine without using variables?
sub XMLEncode {
my ($line) = @_;
$line =~ s/&/&/g;
$line =~ s/</</g;
$line =~ s/>/>/g;
return $line;
}
I was thinking something like
sub XMLEncode {
s/&/&/g;
s/</</g;
s/>/>/g;
return $_;
}
but I can't get it to work like that.
-Philip Mak (pmak@aaanime.net)
Re: [OT] How to write this perl sub w/o variables?
Posted by Honza Pazdziora <ad...@informatics.muni.cz>.
On Sun, Apr 29, 2001 at 04:34:40AM -0400, Philip Mak wrote:
>
> I was thinking something like
>
> sub XMLEncode {
local $_ = shift;
> s/&/&/g;
> s/</</g;
> s/>/>/g;
> return $_;
> }
--
------------------------------------------------------------------------
Honza Pazdziora | adelton@fi.muni.cz | http://www.fi.muni.cz/~adelton/
.project: Perl, DBI, Oracle, MySQL, auth. WWW servers, DBD::XBase.
------------------------------------------------------------------------
Re: [OT] How to write this perl sub w/o variables?
Posted by Stas Bekman <st...@stason.org>.
On Sun, 29 Apr 2001, Philip Mak wrote:
> Is it possible to rewrite this perl subroutine without using variables?
>
> sub XMLEncode {
> my ($line) = @_;
> $line =~ s/&/&/g;
> $line =~ s/</</g;
> $line =~ s/>/>/g;
> return $line;
> }
>
> I was thinking something like
>
> sub XMLEncode {
> s/&/&/g;
> s/</</g;
> s/>/>/g;
> return $_;
> }
>
> but I can't get it to work like that.
don't reinvent the wheel, use CPAN:
# get the encoding sub right
if ($ENV{MOD_PERL}) {
require Apache::Util; # much faster! XS/C code!
*encode = \&Apache::Util::escape_html;
} else {
require HTML::Entities;
*encode = \&HTML::Entities::encode;
}
then call encode($mytext);
not talking about the fact that your code is highly inefficient (you run
s/// 3 times!!!), at least use a hash:
%map = (
'&' => '&',
'<' => '<',
'>' => '>',
);
sub encode { $_[0] =~ s/(&|<|>)/$map{$1}/g; }
note that this will fail: encode("hello"), because you will try to modify
a constant string (versus, $a = 'hello'; encode($a)).
hope this helps...
_____________________________________________________________________
Stas Bekman JAm_pH -- Just Another mod_perl Hacker
http://stason.org/ mod_perl Guide http://perl.apache.org/guide
mailto:stas@stason.org http://apachetoday.com http://logilune.com/
http://singlesheaven.com http://perl.apache.org http://perlmonth.com/