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

Hi all

I am having trouble with the below code. Instead of waiting for the prompt which looks something like '1>', each of the lines in the file is being sent without waiting for the prompt. If I take it out of the foreach loop, and explicitly

$exp->send

$exp->expect

for each line, then it works fine. But, I need to get it to send each line of the file, wait for the prompt, send the next line, rinse, repeat.

It seems that perl is not waiting for the $exp->expect to be true before looping to next. How can I fix this? Thanks.

#now send each line of the $isqlcommandfile to isql foreach my $line (<ISQLCOMMANDFILE>) { #usleep(4000); chomp $line; $exp->send("$line\n"); $exp->expect(2000, '-re', '\d+\> ') if (! $line=~m/^\s*exit\s*$/i); } $exp->soft_close();

Replies are listed 'Best First'.
Re: problems using Expect.pm in foreach loop
by keszler (Priest) on Sep 10, 2011 at 05:40 UTC
    Why are you checking if $line contains 'exit' each time you _expect_ a response?
      indeed, what if you run your code without the check?

        The reason I was doing that is because if the '/^\s*exit\s*$/i' matched, that means the isql code is an exit statement, which would cause the isql program to terminate, thus I would not want to expect another '\d+\>' prompt.

        Taking the if statement out, makes the code work as expected, although I'm not sure why. Also, it does not seem to cause a problem when the exit statement is given. It doensn't hang expecting another prompt. The program just exits, but I really don't understand why.

        Can someone help explain? What if I do want to only expect a prompt if the $line does not match '/^\s*exit\s*$/i' ?

        Thanks for helping me get this code working and thanks in advance for helping me understand the behavior better.

        -G