[lug] Re: Self-modifying Perl

Zan Lynx zlynx at acm.org
Wed Oct 4 18:07:35 MDT 2006


On Wed, 2006-10-04 at 15:52 -0600, Bill Thoen wrote:
> Never mind... I just discovered the 'eval' command and answered my own
> question!
> 
> On Wed, Oct 04, 2006 at 03:39:51PM -0600, Bill Thoen wrote:
> > Is there a way to execute Perl regex commands as variables within Perl? For
> > eaxmple, this doesn't work, but is something like it possible?
> > 
> > #!/usr/bin/perl
> > 
> > my $cmd = 's/\d/!/g';
> > while (<>) {
> >   chop;
> >   $cmd;
> >   print "$_\n";
> > }
> > 
> > What I'd like to be able to do is execute $cmd as if it were the substitute
> > regex. Ultimately, $cmd would be "fed" from a data file, which would allow
> > the program to behave differently depend on which data file I feed it.

eval is alright, but can be horribly inefficient.  I've rewritten
scripts at work that used variable regexes and sped them up over 20
times.  That is significant over a 1 GB log file!

Use a stored regex.  They're like one-time eval regexes (see the /o
option) but can be changed while /o cannot.

It'd be something like:

$find = shift @ARGV || "0";
$rep  = shift @ARGV || "1";
$re = qr/$find/;

print "find $find rep $rep\n";

while( <> ) {
        s/$re/$rep/g;
        print;
}

-- 
Zan Lynx <zlynx at acm.org>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20061004/c8ce1774/attachment.pgp>


More information about the LUG mailing list