Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Why a regexp won't increment the value of a variable
by almut (Canon) on Nov 24, 2008 at 20:24 UTC | |
|
Re: Why a regexp won't increment the value of a variable
by gmoque (Acolyte) on Nov 24, 2008 at 20:50 UTC | |
|
Re: Why a regexp won't increment the value of a variable
by Anonymous Monk on Nov 24, 2008 at 20:19 UTC | |
|
Re: Why a regexp won't increment the value of a variable
by JavaFan (Canon) on Nov 24, 2008 at 20:40 UTC |