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

So, under 5.005_03 this works fine:
sub changeme{ local $^I = ".$bak"; @ARGV = "somefile"; while (<>) { s/foo/bar/i; print; } }
However, substitute a variable in for bar:
sub changeme{ $myvar = somesub(); local $^I = ".$bak"; @ARGV = "somefile"; while (<>) { s/foo/$myvar/i; print; } }
And nothing happens - it just hangs. Why?

Replies are listed 'Best First'.
Re: Edit in place (part2)
by GrandFather (Saint) on May 01, 2006 at 20:43 UTC

    Seems most likely there is something external going on, like the file is accessed over a slow network or is mapping to the console in some fashion. On the face of it the code is fine.


    DWIM is Perl's answer to Gödel
Re: Edit in place (part2)
by ikegami (Patriarch) on May 01, 2006 at 20:40 UTC

    Dunno, but you could try replacing
    s/foo/$myvar/i;
    with
    substr($_, $-[0], $+[0] - $-[0], $myvar) if /foo/i;

Re: Edit in place (part2)
by CountOrlok (Friar) on May 01, 2006 at 20:40 UTC
    $myvar may have meta characters. See the quotemeta function, i.e. $myvar = quotemeta(somesub());
    -imran
      No, $myvar can safely contain any character. You only need to escape text interpolated into the regexp, not the replace string.
Re: Edit in place (part2)
by davidrw (Prior) on May 01, 2006 at 20:39 UTC
    doesn't answer the "why" (may extra data point??), but does s/foo/$myvar/ie; work?
      No, however it's hanging before the regex. In a truss you see the somesub() and then it sleeps. I'm just grasping at straws, but I feel that it's about the ARGV. The <> is getting mucked somehow.
        Can you post the code that is in somesub()?
        -imran