Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl pipe open issue with ' in command

Tags:

file-io

pipe

perl

I am puzzled, simple code fails to return error for PIPE2 open, but does it for similar PIPE3!
I read perl processes pipe openings differently if there are any meta characters, but I do not know how to write code with correct error check for invalid pipe. How can I check PIPE2 open failed? $? or $! did not pickup error either.
Thanks.

open(PIPE2,"|/bin/echod 'sometxt'")||die "Pipe2 cannot open\n";
print PIPE2 "echoed 2\n";
close PIPE2;

open(PIPE3,"|-","/bin/echod sometxt")||die "Pipe3 cannot open\n";
print PIPE3 "echoed 3\n";
close PIPE3;

From command prompt after execution:

sh: /bin/echod: No such file or directory   
Pipe3 cannot open

This is perl, v5.8.8 built for x86_64-linux-thread-multi

like image 449
user1281461 Avatar asked Mar 29 '26 23:03

user1281461


1 Answers

When you use the fancy "|-" style, you are not specifying a shell command to run, but rather a list of arguments to be passed to the execvp(2) syscall.

open(PIPE2,"|/bin/echod 'sometxt'")      || die "Pipe2 cannot open: $!";
print PIPE2 "echoed 2\n";
close(PIPE2)                             || die "Pipe2 cannot close: $!";

versus

open(PIPE3,"|-","/bin/echod", "sometxt") || die "Pipe3 cannot open: $!";
print PIPE3 "echoed 3\n";
close(PIPE3)                             || die "Pipe3 cannot close: $!";

The second form is used only when you don’t want the shell expanding wildcards, interpreting pipe and redirect symbols, etc. when you pass in variables of unknown content.

The first form is for when you do want that to happen, or when you have constant strings or string of known content in the command. I virtually always use the first form, reserving the second form for tricky situations like

open(GREPPER, "grep $expr @files |")

because it’s a thankless and fairly impossible job trying to figure out the right quoting on $expr there.

like image 137
tchrist Avatar answered Apr 02 '26 14:04

tchrist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!