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

#!/usr/bin/perl
$cmd = qx {id ahmedf};
if($cmd =~ /uid/) {
print "LDAP Ok\n";
exit 0;
}
if($cmd =~ /invalid/i) {
print "Please check LDAP\n";
exit 2;
}
If test user is there I get proper message "LDAP OK" but if test user is not there I get system message "id: invalid user name: "test" rather than message in loop, how can I get the message "Please check LDAP"

Replies are listed 'Best First'.
Re: simple Help
by ccn (Vicar) on Nov 26, 2008 at 07:39 UTC

    There are two options

    • try to redirect stderr: qx{id ahmedf 2>&1} to get error messages in $cmd
    • exit 2; without any condition after the first if block
      Thanks mate, qx{id ahmedf 2>&1} did the trick, thanks heaps . just curious what "2>&1" does in fact
        farhan:

        It tells the command shell to send all output from filehandle 2 (typically STDERR) to filehandle 1 (typically STDOUT). For further details, see perldoc perlop:

        qx/STRING/ `STRING` A string which is (possibly) interpolated and then executed as a system command with "/bin/sh" or its equivalent. Shell wild- cards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected. In scalar... <<<<< SNIP >>>>> ...To capture a command's STDERR and STDOUT together: $output = `cmd 2>&1`;
        ...roboticus
Re: simple Help
by farhan (Novice) on Nov 26, 2008 at 09:20 UTC
    qx{id ahmedf 2>&1} did the trick, thanks heaps
Re: simple Help
by toolic (Bishop) on Nov 26, 2008 at 16:07 UTC
    It may also be useful to check the return status of your qx command using the special variable $?. This may be a more portable solution since I do not get the same system message as you do when it fails. I get "id: test: No such user".
    use strict; use warnings; my $cmd = qx{id ahmedf 2>&1}; if ($?) { print "Please check LDAP\n"; exit 2; } elsif ($cmd =~ /uid/) { print "LDAP Ok\n"; exit 0; }
Re: simple Help
by sathiya.sw (Monk) on Nov 26, 2008 at 08:42 UTC
    use else instead of the second if statement. Then your message "please check LDAP will get printed. But system message also got printed.

      I don't understand why you recommend eval over qx, since these two serve completely different purposes. Care to explain?

      Update: OP has changed, this posting is now irrelevant.