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

Dear monks: I have a text file which contains:

The variable is $var_one.

I think the following program should copy it to STDOUT, and expand variable names found in the file, but it causes an "uninitialized variable" error in the evaluation:
my $var_one; sub copy_file { open(IFILE, "<afile"); while($x = <IFILE>) {$x =~ s|(\$\w+)|$1|eeg; print $x}; close(IFILE); } copy_file();
This works, by bringing the variable inside the sub:
my $var_one; sub copy_file { my $var_one = $var_one; open(IFILE, "<afile"); while($x = <IFILE>) {$x =~ s|(\$\w+)|$1|eeg; print $x}; close(IFILE); }
This works too, and finds the global variable:
my $var_one; sub copy_file { my $x = "<p>The variable is $var_one.</p>"; $x =~ s|(\$\w+)|$1|eeg; print $x; }
If I evaluate only once, I get the name of the variable, from the file, as expected:
sub copy_file { open(IFILE, "<afile"); while($x = <IFILE>) {$x =~ s|(\$\w+)|$1|eg; print $x}; close(IFILE); }
So... the expression s|(\$\w+)|$1|eeg fails only when the variable is outside the sub, and only when called from inside the while statement. How can I force the RE to find the global variable?

Replies are listed 'Best First'.
Re: about scope and s///eeg
by shenme (Priest) on Sep 12, 2003 at 07:36 UTC
    Your example as given is perhaps not what you're really running?   Fixing the example is as simple as adding
    $var_one = 'now defined';
    after the my $var_one;.
      Oops. The global variable is really initialized when defined, as in:
      my $var_one = "a string"; sub copy_file { my $f = shift; open(IFILE, "<$f"); while($x = <IFILE>) {$x =~ s|(\$\w+)|$1|eeg; print $x}; close(IFILE); } copy_file("afile");
        But then you still get warnings?   What I tested with was:
        #!/usr/bin/perl -w use strict; use warnings; my $var_one; $var_one = 'now defined'; sub copy_file { while( my $x = <DATA>) { $x =~ s|(\$\w+)|$1|eeg; print $x; }; } copy_file(); __DATA__ The variable is $var_one.
        As coded above I get the output
        The variable is now defined.
        
        If I comment out the   $var_one =   I see
        Use of uninitialized value in substitution iterator at anon02.pl line 12, <DATA> line 1.
        The variable is .
        
        Any chance the variable name is misspelled in the text file?   When I tried the following data:
        __DATA__
        The variable is $var_one.
        The variable is $var_one2.
        The variable is $Var_one.
        
        I got error messages:
        The variable is now defined.
        Use of uninitialized value in substitution iterator at anon02.pl line 14, <DATA> line 2.
        The variable is .
        Use of uninitialized value in substitution iterator at anon02.pl line 14, <DATA> line 3.
        The variable is .