Hello Perlmonks,

This might sound a really stupid question, but I have been playing with this for a while and I still don't get the result I am expecting.

I want to read a file line by line and when a certain pattern is matched want to substitute that pattern for something like "$replacement-$counter" where $replacement never changes on the script and $counter comes from a for loop. Basically I have a template that I want to use many times.


Here is my code, I put in red where I hit the problem:

#!/usr/bin/perl use Getopt::Long; use strict; my $template; my $replacement; my $prefix; my $total; my $counter; my @template; GetOptions ( "template=s" => \$template, "replacement=s" => \$replacement, "prefix=s" => \$prefix, "total=i" => \$total, ); open FH, "< $template" or die "Couldn't open the file $template\n"; @template = <FH>; close FH;
for ($counter=0; $counter<$total; $counter++) { foreach (@template) { $_ =~ s/$replacement/${prefix}-${counter}/; print $_; } }

My Template file looks like this:

enable config protocol mpls lsp name __replaceme__

And I always get the initial value of $counter in the replacement like this:

# ./create_rsvp_lsp.pl -template lsp_template.tpl -replacement "__name +__" -prefix "lsp_to_1.1.118.152" -total 5 enable config protocol mpls lsp name lsp_to_1.1.118.152-0 enable config protocol mpls lsp name lsp_to_1.1.118.152-0 enable config protocol mpls lsp name lsp_to_1.1.118.152-0 enable config protocol mpls lsp name lsp_to_1.1.118.152-0 enable config protocol mpls lsp name lsp_to_1.1.118.152-0

What am I doing wrong here?

Many thanks!


In reply to Why a regexp won't increment the value of a variable by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.