in reply to redirecting output in perl

Update: I rewrote this post after doing some testing.

The string is passed to the DOS shell cmd.exe to parse and execute. cmd.exe's directory should be in the PATH. (perl should probably check COMSPEC, but it doesn't.) You need to put cmd.exe in the current directory, or place it's directory in the PATH.

system("c:\windows\system32\cmd.exe /c echo hello > tmp.log"); doesn't help.

Changing sh= in Config.pm doesn't help.

That means if you're in Win95/98/ME, you're in trouble because cmd.exe is for WinNT/2K/XP. You could recompile perl yourself...

btw,
$tmp_log = `echo hello`;
might be more along the lines of what you want than
system("echo hello > tmp.log");,
but that won't fix your problem.

Replies are listed 'Best First'.
Re^2: redirecting output in perl
by Anonymous Monk on Sep 20, 2004 at 18:52 UTC
    Thank you so much for your reply. I am using WinXP.

    In fact, the command:
     system('echo hello'); works fine...

    But, redirecting a command output to the file does not work.

    Also, is there an easier way I can create a file other than:
    unless ( -e $file ) { open ( FH, " > $file" ); close (FH); }


    Thank you,
    Lily

      Odd, both
      system("echo hello > tmp.log");
      and
      system("echo hello");
      work for me, as they should.

      As for creating a file, opening it for write-append does the trick:
      { local *FH; open(FH, '>>', $file) or die("...: $!\n"); }

      Perl only uses a shell to execute commands if the command string contains shell metacharacters, like the greater-than symbol used to redirect output. That's why it works with no redirection, but breaks with it.

      The solution, as others have said, is probably to add something to your path that has cmd.exe. Generally a Windows system will have this by default, so you may want to look into why your PATH doesn't have this.

      A quick hack that might help is something like:

      $ENV{PATH} .= ";c:\\windows\\command". ";c:\\windows\\system32". ";c:\\winnt\\system32";