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?

In reply to about scope and s///eeg by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.