Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

How can I increment a var in a substitution?

by kingman (Scribe)
on Aug 09, 2001 at 23:06 UTC ( [id://103568]=perlquestion: print w/replies, xml ) Need Help??

kingman has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I just read [id://20361|How would I replace the string 'Red1' with $Red1?]
But I still can't figure this out. Here's the code:
$n = 0; $html_file_slurped_to_a_scalar =~ s/<img .*?>/«TOKEN_$n++»/gis;
This turns all img links into «TOKEN_0++»; $n interpolotes but doesn't increment.
If I add the /e modifier, the complier chokes when it tries to evaulate «
Unrecognized character \xAB at /path/foo line 25.
Maybe I'm trying to do too much but I'd like to avoid the following loop if I can:

evaluate $html_file_slurped_to_a_scalar
change the first image tag to «TOKEN_$n»
increment $n

Any suggestions?

Replies are listed 'Best First'.
Re: How can I increment a var in a substitution?
by suaveant (Parson) on Aug 09, 2001 at 23:11 UTC
    the e modifier means evaluate right side of substitution as perl code... so you need /'<<TOKEN_'.$n++.'>>'/ to make it into perl code that makes the string you want to substitute... you could also do...
    $html_file_slurped_to_a_scalar =~ s/<img .*?>/«TOKEN_${\($n++)}»/gis;
    which is a little trick to put code into an interpolated string

                    - Ant
                    - Some of my best work - Fish Dinner

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2025-03-26 08:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When you first encountered Perl, which feature amazed you the most?










    Results (67 votes). Check out past polls.

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.