Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

replace text with function ?

by 2xlp (Sexton)
on Jan 12, 2009 at 03:10 UTC ( #735593=perlquestion: print w/ replies, xml ) Need Help??
2xlp has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to parse a document and rewrite certain tags
for example the document has stuff like this in it:
<img id="image-1" src="http://site.com/a.gif" />
i know how to pull the text via a regex easily
my $regex= qr|<img id="image-(\d*) src="http://site.com/(\w*)" />
however now i need to replace the node's contents with the output of a function ( which is based on the matches generated ).
can someone please point me in the right direction? this seems like it should be rather simple, but i've been working all weekend and am having trouble wrapping my head around this.

Comment on replace text with function ?
Select or Download Code
Re: replace text with function ?
by Fletch (Chancellor) on Jan 12, 2009 at 03:26 UTC

    You want to look at the /e modifier for s/// in perlretut and perlop.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      A simple example:
      s/(\d+)/ sprintf('%03d', $1) /eg;
      that is it! thank you!
Re: replace text with function ?
by ww (Bishop) on Jan 12, 2009 at 13:18 UTC

    Note, however, that -- as originally posted --your regex does NOT match (has a typo?).

    #!/usr/bin/perl -lw use strict; # [id://735593] my $string = '<img id="image-1" src="http://site.com/a.gif" />'; my $regex = qr|<img id="image-(\d)" src="http://site.com/(\w\.\w+)" /> +|; # works # ^^^^^^^ + < modified here if ( $string =~ /$regex/ ) { print "\$regex matches: $1 and $2"; } else { print "No match in $regex"; } my $OPregex= qr|<img id="image-(\d*) src="http://site.com/(\w*)" />|; + # OP's with (added) terminating "|;" if ( $string =~ /$OPregex/ ) { print "\$OPRegex matches: $1 and $2"; } else { print "no match in \$OPRegex"; }

    Output:

    perl F:\_wo\pl_test\735593.pl $regex matches: 1 and a.gif no match in $OPRegex
      ha ha, yes! nice catch!

      that wasn't the real regex -- stuff is working PERFECTLY now.

      thanks to all!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://735593]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2014-09-16 10:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (0 votes), past polls