[OT] How to write this perl sub w/o variables?

2001-04-29 Thread Philip Mak

Is it possible to rewrite this perl subroutine without using variables?

sub XMLEncode {
my ($line) = @_;
$line =~ s//amp;/g;
$line =~ s//lt;/g;
$line =~ s//gt;/g;
return $line;
}

I was thinking something like

sub XMLEncode {
s//amp;/g;
s//lt;/g;
s//gt;/g;
return $_;
}

but I can't get it to work like that.

-Philip Mak ([EMAIL PROTECTED])




Re: [OT] How to write this perl sub w/o variables?

2001-04-29 Thread Honza Pazdziora

On Sun, Apr 29, 2001 at 04:34:40AM -0400, Philip Mak wrote:
 
 I was thinking something like
 
 sub XMLEncode {

local $_ = shift;

 s//amp;/g;
 s//lt;/g;
 s//gt;/g;
 return $_;
 }

-- 

 Honza Pazdziora | [EMAIL PROTECTED] | 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?

2001-04-29 Thread Stas Bekman

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//amp;/g;
 $line =~ s//lt;/g;
 $line =~ s//gt;/g;
 return $line;
 }

 I was thinking something like

 sub XMLEncode {
 s//amp;/g;
 s//lt;/g;
 s//gt;/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 = (
  '' = 'amp',
  '' = 'lt',
  '' = 'gt',
);

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:[EMAIL PROTECTED]   http://apachetoday.com http://logilune.com/
http://singlesheaven.com http://perl.apache.org http://perlmonth.com/