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); }
In reply to about scope and s///eeg by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |