perlexpect.pm

Perl expect module not able to understand


I am new to Perl. I am using Perl Expect module to automate a simple prog but the output is mismatched. This is my Perl code which I wanted to be automated

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use Path::Tiny qw(path);
use IO::Prompter;


my $username= prompt "What is your name";
my $hry= prompt "How are you";
my $age= prompt "How old are you";

and this is my Expectfile code..

#!/usr/bin/perl
use strict;
use warnings;

use Expect;
my $cmd='perl';
my @param=qw(Welcome.pl);
my $exp = Expect->spawn($cmd,@param) or die "Cannot spawn $cmd: $!\n";

$exp->expect (1,"What is your name");
$exp->send("Alen\r");

$exp->expect (1,"Alen\rHow are you");
$exp->send("Fine\r");

$exp->expect (1,"Fine\rHow old are you");
$exp->send("21\r");
$exp->hard_close();

This is the output I'm getting

admin3@admin3-VirtualBox:~/Desktop$ perl WelcomeExpect.pl
 What is your name Alen
 Alen
 How are you Fine
 How old are you admin3@admin3-VirtualBox:~/Desktop$

My name is appearing again on the next line and the age input is not at all showing.

New Update-->Now when I'm using soft_close instead of hard_close, my age input is coming. But still, my name input is coming two times. admin3@admin3-VirtualBox:~/Desktop$ perl WelcomeExpect.pl

What is your name Alen
Alen
How are you Fine
How old are you 21
admin3@admin3-VirtualBox:~/Desktop$

Solution

  • The following works for me (Ubuntu 19.04, Expect version 1.35, perl version 5.28.1):

    use strict;
    use warnings;
    use Expect;
    
    my $cmd='perl';
    my @param=qw(Welcome.pl);
    my $exp = Expect->new();
    $exp->spawn($cmd, @param) or die "Cannot spawn $cmd: $!\n";
    
    $exp->expect (1, "What is your name ");
    $exp->send("Alen\n");
    $exp->expect (1, "Alen");
    $exp->send("Fine\n");
    $exp->expect (1, "\nHow are you Fine");
    $exp->send("21\n");
    $exp->expect (1, "\nHow old are you 21");
    $exp->soft_close();