Here is a very brute force method that replaces all text
items 'foo' with 'bar' using
HTML::Template
HTML::Parser
. The
idea is to set callbacks everytime:
- a start tag is encountered
- the inside text element is encountered
- the end tag is encountered
For the first and third cases, we simply regurgitate what
we found to STDOUT. For the middle case, we substitute.
Hope this helps. :)
use strict;
use warnings;
use HTML::Parser;
my $parser = HTML::Parser->new(api_version => 3);
$parser->handler(start => \&start, 'self,tagname,attr');
$parser->handler(text => \&text, 'self,dtext');
$parser->handler(end => \&end, 'self,tagname');
$parser->parse(q|<foo bar="qux" baz="foo">foo</foo>|);
sub start {
my ($parser,$tag,$attr) = @_;
print "<$tag";
# we lose the original order of attribs, but we'll live ;)
print qq| $_="$attr->{$_}"| for keys %$attr;
print ">";
}
sub text {
my ($parser,$text,$attr) = @_;
$text =~ s/foo/bar/g;
print "$text";
}
sub end {
my ($parser,$tag) = @_;
print "</$tag>";
}
UPDATE:
Thanks
hiseldl ... maybe it really is time for me to
switch from HTML::Template to TT! :D
jeffa
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.