Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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="" />
i know how to pull the text via a regex easily
my $regex= qr|<img id="image-(\d*) src="\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.

Replies are listed 'Best First'.
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 (Archbishop) 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="" />'; my $regex = qr|<img id="image-(\d)" src="\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="\w*)" />|; + # OP's with (added) terminating "|;" if ( $string =~ /$OPregex/ ) { print "\$OPRegex matches: $1 and $2"; } else { print "no match in \$OPRegex"; }


    perl F:\_wo\pl_test\ $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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://735593]
Approved by ww
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2018-02-18 05:45 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (250 votes). Check out past polls.