Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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
[oiskuu]: Someone needs to re-read How do I use the power of consideration responsibly? carefully. Consideration is not intended for stamping out humor, AFAIK.
[oiskuu]: E.g. Re^3: Big thank you to the Perl community. is surely dry humor (not mine). Don't they teach humor in german schools!?
[LanX]: you don't see the whole picture

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (13)
As of 2017-04-27 19:49 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (512 votes). Check out past polls.