Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Simple computation - adding two values

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

use Expect;

my $e = Expect->new;
#$e->raw_pty(1);

$e->spawn("bc") or die "Cannot run bc\n";

$e->expect(1, -re => "warranty'\.") or die "no warranty\n";

$e->send("23+7\n");
$e->expect(1, -re => '\d+\+\d+') or die "no echo\n";
print $e->match, "\n";

$e->expect(1, -re => '\d+') or die "no sum\n";
my $match = $e->match;

if ($match eq "30") {
    print "Success\n";
} else {
    print "Failure. Received $match\n";
}

$e->send("quit\n");


  • raw_pty turns off echo
  • spawn starts the external program
  • expect(timeout, regex) return undef if failed
  • timeout is in seconds, 0 means check once, undef means wait forever
  • send - as if the user was typing at the keyboard