note
crazyinsomniac
Here is my take on this. It is pretty similar, except the tag attributes ( src=... alt=...)are printed in the order they appear in the original text (you could also achieve this, if you used 'attrseq'). I however, use HTML::TokeParse and URI, and this one only modifies absolute urls (like links to other http|ftp sites, unlike yours, which will turn a 'mailto:foo@bar.baz.com' into $new_url.'mailto:foo@bar.baz.com'), but can easily be extended to modify any kind of URIs (that is Uniform Resource Identifier, not just Locator's ;D). If you were goning to make this more modular, i'd sugguest not doing it this way (extend HTML::Parser instead, but for a script, this is the perfect strategy, [#IN MY HUMBLE OPINION|IMHO]). Here goes:
<CODE>
#!/usr/bin/perl -w
use strict;
use LWP::Simple qw(get);
use HTML::TokeParser;
use URI;
my $new_link = "http://www.baz.com/cgi-bin/doubleclick.cgi?url=";
my $url = $ARGV[0] or die "usage: ". __FILE__ ." http://www.foo.com/bar.html\n";
my $file = get($url) or die "Cannot get the page '$url'\n";
my $P = HTML::TokeParser->new(\$file);
while (my $T = $P->get_token() )
{ # 0 1 2 3 4
if($$T[0] eq "S") # ["S", $tag, $attr, $attrseq, $text]
{
if($$T[1] eq 'img')
{
&handle_link($T, 'src');
}
elsif($$T[1] eq 'a')
{
&handle_link($T, 'href');
}
elsif($$T[1] eq 'script')
{
&handle_link($T, 'src');
}
else # nothing we wanna change
{
print $$T[4];
}
}
elsif($$T[0] =~ /^(?:E|PI)$/ ) # end tag | process instruction
{
print $$T[2];
}
elsif($$T[0] =~ /^(?:T|C|D)$/ ) # text | comment | declaration
{
print $$T[1];
}
} # endof while (my $T = $P->get_token)
sub handle_link
{
my ( $T, $A) = @_;
my $URI = new URI( $$T[2]->{$A} );
# 0 1 2 3 4
# ["S", $tag, $attr, $attrseq, $text]
my $scheme = $URI->scheme();
if( $scheme and $scheme =~ /^(http|ftp)$/i ) # only if its not relative url (yes scheme)
{
$$T[2]->{$A} = $new_link . $URI->path(); # path is escaped
}
print "<$$T[1]",
( map { qq| $_="$$T[2]->{$_}"| }
@{$$T[3]}
)
, '>';
}
</CODE>
<P> <BR>
<FONT SIZE=3><a href="/index.pl?node=crazyinsomniac&lastnode_id=1072">___craz<b><i>y</i></b>insomniac_______________________________________</a><br>
<TT>Disclaimer: Don't blame. It came from inside the <a href="/index.pl?node_id=21786&WROTE_QUOTE=Of all the things I've lost, I miss my mind the most.">void</a> </TT></FONT><BR>
<FONT SIZE=2><TT>perl -e "$q=$_;map({chr unpack qq;H*;,$_}split(q;;,q*H*));print;$q/$q;" </TT></FONT>
134076
134076