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

I am converting a bash script that executes many commands. Each
command logs the stderr and stdout to a file. I intended to use
the system command in Perl to the same effect. Here is a contrived
example to illustrate the problem I am running into.
Why does this not work? Why is >> having a problem?
my $logfile = '/tmp/zzzz'; `touch $logfile` if (!(-e($logfile))); if (system( "ls", "-l", "/bin/bash", ">>", "$logfile", "2>&1" )) { print "Nope!\n"; } __END__ bash-2.05b$ perl a1.pl ls: >>: No such file or directory ls: 2>&1: No such file or directory -rwxr-xr-x 1 root root 598580 Sep 18 2003 /bin/bash -rw-rw-r-- 1 nooninmh man 0 Mar 29 18:52 /tmp/zzzz

Replies are listed 'Best First'.
Re: system command has problem with '>>'
by JavaFan (Canon) on Mar 29, 2010 at 23:08 UTC
    If you call system with a list of arguments, no shell is involved. And it's the shell that interprets >>. Your way of calling system means ls is called, with >> as its third argument.

    Use:

    unless (system "ls -l /bin/bash >> $logfile 2>&1") { print "Nope!\n"; }
    instead.

    Further points: 1) there's no need to first create $logfile. The redirection will create it if necessary. 2) system returns 0 on success, following the Unix convention.

Re: system command has problem with '>>'
by Anonymous Monk on Mar 29, 2010 at 23:09 UTC
    Its because you didnt read the documentation clearly. The ls program doesn't know what to do with >> or 2>&1, its not sh/csh/perl -V:sh

    Use systemx from IPC::System::Simple

    use IPC::System::Simple qw[ systemx ]; ...
      Not true. The shell processes '>>', not 'ls', as can be seen from the pastes below.
      Anyone else have any ideas on this?

      $ rm aa
      $ ls example_file.txt >> aa
      $ cat aa
      example_file.txt
      $ ls exam*
      example_file.txt
      $ ls example_file.txt >> aa
      $ cat aa
      example_file.txt
      example_file.txt
        Not true. The shell processes '>>', not 'ls', as can be seen from the pastes below.

        Thats what I said.

        Anyone else have any ideas on this?

        Like I said, use IPC::System::Simple systemx, it process >> like the shell without invoking the shell, or like JavaFan said, invoke the shell