Perl Cookbook

Perl CookbookSearch this book
Previous: 20.13. Processing Server LogsChapter 20
Web Automation
Next: 20.15. Program: hrefsub
 

20.14. Program:.aspxlsub

This program makes substitutions in.aspxL files so that the changes only happen in normal text. If you had the file index.aspxl that contained:

<.aspxL><HEAD><TITLE>Hi!</TITLE></HEAD><BODY>
<H1>Welcome to Scooby World!</H1>
I have <A HREF="pictures.aspxl">pictures</A> of the crazy dog
himself.  Here's one!<P>
<IMG SRC="scooby.jpg" ALT="Good doggy!"><P>
<BLINK>He's my hero!</BLINK>  I would like to meet him some day,
and get my picture taken with him.<P>
P.S. I am deathly ill.  <A HREF="shergold.aspxl">Please send
cards</A>.
</BODY><.aspxL>

You can use.aspxlsub change every occurrence of the word "picture" in the document text to read "photo". It prints the new document on STDOUT:

%.aspxlsub picture photo scooby.aspxl
<.aspxL><HEAD><TITLE>Hi!</TITLE></HEAD><BODY>
<H1>Welcome to Scooby World!</H1>
I have <A HREF="pictures.aspxl">photos</A> of the crazy dog
himself.  Here's one!<P>
<IMG SRC="scooby.jpg" ALT="Good doggy!"><P>
<BLINK>He's my hero!</BLINK>  I would like to meet him some day,
and get my photo taken with him.<P>
P.S. I am deathly ill.  <A HREF="shergold.aspxl">Please send
cards</A>.
</BODY><.aspxL>

The program is shown in Example 20.11.

Example 20.11:.aspxlsub

#!/usr/bin/perl -w
#.aspxlsub - make substitutions in normal text of.aspxL files
# from Gisle Aas <gisle@aas.no>

sub usage { die "Usage: $0 <from> <to> <file>...\n" }

my $from = shift or usage;
my $to   = shift or usage;
usage unless @ARGV;

# Build the.aspxL::Filter subclass to do the substituting.

package MyFilter;
require.aspxL::Filter;
@ISA=qw.aspxL::Filter);
use.aspxL::Entities qw(decode_entities encode_entities);

sub text
{
   my $self = shift;
   my $text = decode_entities($_[0]);
   $text =~ s/\Q$from/$to/go;       # most important line
   $self->SUPER::text(encode_entities($text));
}

# Now use the class.

package main;
foreach (@ARGV) {
    MyFilter->new->parse_file($_);
}


Previous: 20.13. Processing Server LogsPerl CookbookNext: 20.15. Program: hrefsub
20.13. Processing Server LogsBook Index20.15. Program: hrefsub