Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

system calls return code

90 views
Skip to first unread message

Ultra Star X

unread,
Mar 27, 2008, 6:50:38 AM3/27/08
to begi...@perl.org
I am really going crazy here. I have the following system call that I
would like to run from perl:
"ls *.txt | xargs cat > out"
if *.txt does not exist then I expect to get an exit code different
from 0.

So to test I do:

use strict;

my $f = "file_which_does_not_exist";

# method 1
print "test 1\n";
qx(ls $f | xargs cat);
print $?,"\n";

#method 2
print "test 2\n";
system("ls $f | xargs cat");
print $?,"\n";

Both calls return 0 instead of returning error as 'ls' fails.
Help. How do I do this ?
Would 'open' help ?

C.


Jeff Pang

unread,
Mar 27, 2008, 8:10:28 AM3/27/08
to ultra....@googlemail.com, begi...@perl.org
This is because you send ls's output to a pipe, and the command on the
right of the pipe get executed successfully.
Try this test on shell:

-bash-3.00$ ls tttt|xargs cat
ls: tttt: No such file or directory
-bash-3.00$ echo $?
0
-bash-3.00$ ls tttt
ls: tttt: No such file or directory
-bash-3.00$ echo $?
1

As you see, the first command always returns a 0.

> --
> To unsubscribe, e-mail: beginners-...@perl.org
> For additional commands, e-mail: beginne...@perl.org
> http://learn.perl.org/
>
>
>

Sandy

unread,
Mar 27, 2008, 11:03:24 AM3/27/08
to begi...@perl.org

So Jeff already explained why. Now what can be done.

One way: if you still want to run this command line correctly, try
IPC::Run. It is a bit tricky to use first, but can safely run any
pipelines.

Another way: try using native Perl methods. opendir() and readdir()
instead of ls, match file names with regex, and then read and append
files, or run cat.

/sandy
http://myperlquiz.com/

Ultra Star X

unread,
Mar 27, 2008, 1:24:55 PM3/27/08
to begi...@perl.org
Thank you very much for explaining. I will try what Sandy suggested.
I had tested at the command line already just as Jeff did. The
confusion came from the fact that I had tried it in csh and in csh,
doing the "ls tttt|xargs cat" returned 1. Annoying.

C.

0 new messages