2

Why is this exists check returning different results for pwd versus the other examples? What's happening here?

[me@unixbox1:~/perltests]> cat testopensimple.pl
#!/usr/bin/perl

use strict;
use warnings;

# |<command> for writing
# <command>| for reading

testopen("| pwd");
testopen("pwd |");
testopen("| hostname");
testopen("| cd");
testopen("| sh");
testopen("| sleep 2");

sub testopen {
        my $command = shift;

        print "Exists: " . (-e $command ? "true" : "false") . "\n";
        print "testopen($command)\n";
        eval {
                open(my $fh, $command) or die "$! $@";
                my $data = join('', <$fh>);
                close($fh) or die "$! $@";
                print $data . "\n";
        };
        if ($@) {
                print $@ . "\n";
        }
}

[me@unixbox1:~/perltests]> perl testopensimple.pl
Exists: true
testopen(| pwd)
/home/me/perltests

Exists: true
testopen(pwd |)
/home/me/perltests

Exists: false
testopen(| hostname)
unixbox1

Exists: false
testopen(| cd)

Exists: false
testopen(| sh)

Exists: false
testopen(| sleep 2)

Update:

I'm not convinced that it's a shell built-in vs external command issue. Try it with a command like netstat which is external. pwd is the only command I've found thus far that returns true on the exists check with pipes.

Update 2:

Through the several iterations of testing I was doing, files named '| pwd' and 'pwd |' ended up being created. That explains what I'm seeing. Thanks.

0

1 Answer 1

3

-e '| pwd' will only return true if you have a file named | pwd in the current directory.

-e 'pwd |' will only return true if you have a file named pwd | in the current directory.

$ perl -E'say -e "| pwd" ? 1 : 0'
0

$ touch '| pwd'

$ perl -E'say -e "| pwd" ? 1 : 0'
1

$ perl -E'say -e "pwd |" ? 1 : 0'
0

$ touch 'pwd |'

$ perl -E'say -e "pwd |" ? 1 : 0'
1
2
  • That seems to be what happened here. I was also doing some testing with open() using < (read) and > (write) indicators which in turn created the '| pwd' and 'pwd |' files. Thanks.
    – user255205
    Aug 1, 2011 at 19:48
  • @user255205: You can do pipes with 3-arg open, specifying |- or -| as the second arg. See the "fortune" example in perldoc.perl.org/perlopentut.html
    – ysth
    Aug 1, 2011 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.