Variable taking garbage value inside a loop while calling a command line instance in Perl

StackOverflow https://stackoverflow.com/questions/9223434

  •  28-04-2021
  •  | 
  •  

質問

do
{
    print"CHOOSE ANY OF THE FOLLOWING OPTIONS:\n";
    print"==========================================\n";
    print"1-LOGIN & LOGOUT\n";
    print"2-MAKE CALL\n";
    print"3-EXIT\n";
    print"==========================================\n";
    print("\nENTER YOUR OPTION: ");
    $option=<>;
    if($option==1)
    {
        print("IN THE LOGIN & LOGOUT SCENARIO\n");
        &Login_logout();
    }
    elsif($option==2)
    {
        print("IN THE MAKE CALL SCENARIO\n");
    }
    elsif($option==3)
    {
        print("\nEXITING...\n");
        exit(0);
    }
    else
    {
        print"\nINSERT A VALID OPTION...!!!\n";
    }
}while(1);

Here the subroutine Login_logout() calls a SIPp instance(command line instance). After the successful completion of the command line instance the the scalar $option takes some garbage value and hits the else condition and prints the line "INSERT A VALID OPTION...!!!". This process continues infinetly until force closing the Konsole.

Can anybody tell me where I am wrong in the script.

役に立ちましたか?

解決

I think the problem that your external program call modify/redirects the STDIN, that way it is reads some garbage.

Set autoflush:

$|=1;

If you do not need the stdin/stderr on your external call, close explicitly it like this or redirects it to a file:

`sip.sh >&- 2>&- <&-`

or close just the stdin

`sih.sh <&-`

If I am correct this trick is works under recent ksh and bash only. At least under ksh :-)

regards,

他のヒント

Remember that <> takes a line rather then a string, so removing return (CR/LF, etc.) is needed.

...
$option=<>;
chomp $option; ## chomp removes the tailing return
if($option eq '1')
...

do { }while(1); this is nothing but infinite loop only, no condition check so it will loop infinitely, more over try using $option=<STDIN>;

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top