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

Hi, I have the following problem: in my program, at a certain time, I make a substitution of variables of an inputed text. Here's the code:
$ncat += 1; $init_name = "init_$ncat"; open(FILE,">>$filename"); foreach $l(@header){ $l =~ s/#init_name/$init_name/gi; print FILE $l; }
The problem is that the variable #init_name is always substituted by init_0 (the first value) and doesn't increase. If I put:
$ncat += 1; $init_name = "init_$ncat"; open(FILE,">>$filename"); foreach $l(@header){ print #$ncat\n"; $l =~ s/#init_name/$init_name/gi; print FILE $l; }
it shows the variable increasing in the print!!! What am I doing wrong? Kind regards, Kepler

Replies are listed 'Best First'.
Re: Problem with a replacement
by GrandFather (Saint) on Mar 13, 2011 at 22:36 UTC
    What am I doing wrong?
    1. Not using strictures (use strict; use warnings;)
    2. Not using a lexical file handle
    3. Not using three parameter open
    4. Not checking the result from open
    5. Not indenting code
    6. Not providing runnable sample code that demonstrates your problem
    7. Not showing actual output from your sample code
    8. Not showing expected output from your sample code

    There may be logic or other errors in your code too, but it's not clear what you are trying to do to be sure where such errors may be. However, by the time you've cleaned up all the items on the list above you'll probably have cleaned up your other error to.

    True laziness is hard work
Re: Problem with a replacement
by samarzone (Pilgrim) on Mar 14, 2011 at 09:57 UTC

    When you write

    $init_name = "init_$ncat"

    $init_name is assigned a value. Now no matter how many times you change the value of $ncat you don't change the value of $init_name

    Try printing value of $init_name instead of $ncat

    --
    Regards
    - Samar