Expect in Perl - a short explanation and a practical example
Archive - Originally posted on "The Horse's Mouth" - 2010-10-22 08:20:46 - Graham Ellis
Around 20% of delegates on our Tcl Courses are using Tcl because of the Expect package that extends it to "choreograph" interaction with other systems and processes, and yet the Expect module in Perl (Expect.pm) is decidedly niche and we cover it on our Perl for Larger Projects course only on request. But it *is* very useful ...
So - what does Expect on Perl do?
It allows you to spawn a process so that you can replace your terminal interaction with an automated script. You then send any necessary text to that process (as if typed from the keyboard), and you tell your Perl program what to expect back ... and that can be a specific piece of text, a regular expression match, and end of file, or a timeout.
I've written a complete [source code here] for the delegates on this week's course, and taken the example of "pinging" half a dozen different hosts on the Internet for which we are responsible or have an interest in; If I run the script, I get a report from each of the computers as six pings are run, results are grabbed, analysed and tabulated.
Notes:
a) Just like Tcl's Expect, multiple processes can be controlled at the same time; in the example just published, I've only used a single process at a time to help you learn.
b) In Tcl, you would use expect_out to return to you the part of the buffer that's passed over before the match string is found. In Perl, you don't have that global variable, but you do have methods such as before. It's quite hard to find examples of this ... so here's a sample in which I capture a round trip time from deep in a line and echo out just the round trip time itself: