in reply to In place edit does not work on Windows

The filename is proper. Please check below

I wrote this small perl code and this works fine. But when part of main module, this does not work.

my $files = "D:\\Documents and Settings\\All Users\\Application Data\\ +cmd-op928.output"; { local ($^I, @ARGV) = ('.bak', $files); while (<>) { if ($. == 1) { print "<test>\n"; } else { print; } } }

Replies are listed 'Best First'.
Re^2: In place edit does not work on Windows
by Anonymous Monk on Mar 22, 2012 at 10:35 UTC

    But when part of main module, this does not work.

    Maybe you should show that instead

      Here below is the actual snippet from the main module. This does not work.
      { # Need to add tags of <vom> and <\vom> at the # start and end of the file # Doing this below, but in a different block # of code to not disturb ARGV $out->[1] =~ s/\\/\\\\/g; # for windows local @ARGV = ($out->[1]); local $^I = '.bk'; while (<>) { if ($. == 1) { print "<vom>\n"; } else { print; } } open(APP, ">>$out->[1]"); print APP "\n</vom>\n"; close(APP); }
        $out->[1] =~ s/\\/\\\\/g; # for windows

        What is this line supposed to do? What does $out->[1] contain, and what should it contain afterwards?

        I think you're making it way too complicated. In-place editing, when you don't know what you're doing, can wipe out your files. And besides, it's not really editing in-place. It makes an optional backup copy of the file, but it always writes a new file.

        There's probably a module for this (such as Iterator::Diamond, noted here), but it's easy enough to do yourself also. Here's something simple, that is probably more reliable than what you're doing.

        # Assumes you are using strict -- RIGHT? { # Need to add tags of <vom> and <\vom> at the start and # end of the file. # Changing '\' to '\\' is not wrong, but you can also use # '/' on Windows. Perl handles it just fine, and it's a lot # easier to read. It's optional here since you're not dealing # with the filenames directly. $out->[1] =~ s{\\}{/}g; # First, create a backup name and rename the original file. This # creates your backup file, and we'll create your "original" in # a moment. my $bk = $out->[1] . ".bk"; rename $out->[1], $bk; # Open the backup for input. open my $f, '<', $bk or die $!; my $data; # Use this to capture data. # Old-style slurp mode. { local $/ = undef; $data = <$f>; } # Now open the original filename, reusing the filehandle, and # write to it. open $f, '>', $out->[1] or die $!; print $f "<vom>\n", $data, "\n</vom>\n"; close $f; # All done. }
        --marmot