Perl door open problem with "in command"

I am puzzled, the simple code does not return an error for PIPE2, but it does for a similar PIPE3!
 I've read perl handles pipe openings differently if there are any metacharacters, but I don't know how to write code with correct error checking for an invalid pipe. How can I check if PIPE2 is open? $?

or $!

the error did not work either.
Thank.

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 the command line after execution:

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

      

It's perl, v5.8.8

built forx86_64-linux-thread-multi

+3


source to share


2 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) system call.

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

      

against

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

      



The second form is only used when you don't want the shell to expand wildcards, interpret strings and redirect characters, etc., when you were passing in variables of unknown content.

The first form is for when you want it, or when there are constant lines or a line of known content in the command. I almost always use the first shape, leaving the second shape for tricky situations like

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

      

because its a thankless and rather impossible job trying to figure out the correct quote on $expr

there.

+2


source


(as discussed in the comments) In the case of a function open

with a pipe |

(and not |-

or -|

), the failure of the open function can be handled in close

the file descriptor.

This is how I would do it



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

      

+1


source







All Articles