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

Fellow Monks,
I am using telnet for changing the directory in the remote server using my perl script.This is the line for changing the directory,
$rad = $telobj -> cmd ("cd /usr/local/etc/httpd/logs");
I have to check if the change command is executed successfully,then proceed to next block of statements, Eg.
if($rad){ //block of statement }else{ print"Directory not found\n"; }
But the $rad value is alwasy found as 1 even if the command is failing.How to solve this monks,
Thanks.

Replies are listed 'Best First'.
Re: How to check if the change command is success in telnet
by shmem (Chancellor) on Jun 27, 2006 at 07:28 UTC
    The cmd method of a telnet object returns a list, so if you have a scalar at the left of your assignment operator ( = ), you evaluate the returned list in scalar context, and the number of elements of the list will be assigned to $rad.

    To assign the first element of that list to $rad do the following:

    ($rad) = $telobj -> cmd ("cd /usr/local/etc/httpd/logs");

    This way the left hand side (lhs) of the assignment operator is a list, and its first element - $rad - will be assigned the first value of the list returned by the cmd method. Note that $rad is enclosed in parens, which makes the lhs a list statement.

    To check whether the previous cd command has been succesful, you could do:

    ($rad) = $telobj->("pwd"); if($rad eq '/usr/local/etc/httpd/logs') { print "cd command successful. working directory is $rad\n"; } else { print "cd command failed. working directory is $rad\n"; }
    But it's even easier in fact. The cd shell command doesn't return anything if successful, only on failure. So, you could just say
    ($rad) = $telobj -> cmd ("cd /usr/local/etc/httpd/logs"); if($rad) { die "Can't change directory: $rad\n"; }

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}