Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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:This works, by bringing the variable inside the sub: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 too, and finds the global variable: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); }
If I evaluate only once, I get the name of the variable, from the file, as expected:my $var_one; sub copy_file { my $x = "<p>The variable is $var_one.</p>"; $x =~ s|(\$\w+)|$1|eeg; print $x; }
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?sub copy_file { open(IFILE, "<afile"); while($x = <IFILE>) {$x =~ s|(\$\w+)|$1|eg; print $x}; close(IFILE); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: about scope and s///eeg
by shenme (Priest) on Sep 12, 2003 at 07:36 UTC | |
by Anonymous Monk on Sep 12, 2003 at 15:26 UTC | |
by shenme (Priest) on Sep 12, 2003 at 19:04 UTC |