{
    "mode": "perldoc",
    "parameter": "Expect",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Expect/json",
    "generated": "2026-06-14T04:14:24Z",
    "synopsis": "use Expect;\n# create an Expect object by spawning another process\nmy $exp = Expect->spawn($command, @params)\nor die \"Cannot spawn $command: $!\\n\";\n# or by using an already opened filehandle (e.g. from Net::Telnet)\nmy $exp = Expect->expinit(\\*FILEHANDLE);\n# if you prefer the OO mindset:\nmy $exp = new Expect;\n$exp->rawpty(1);\n$exp->spawn($command, @parameters)\nor die \"Cannot spawn $command: $!\\n\";\n# send some string there:\n$exp->send(\"string\\n\");\n# or, for the filehandle mindset:\nprint $exp \"string\\n\";\n# then do some pattern matching with either the simple interface\n$patidx = $exp->expect($timeout, @matchpatterns);\n# or multi-match on several spawned commands with callbacks,\n# just like the Tcl version\n$exp->expect($timeout,\n[ qr/regex1/ => sub { my $exp = shift;\n$exp->send(\"response\\n\");\nexpcontinue; } ],\n[ \"regexp2\" , \\&callback, @cbparms ],\n);\n# if no longer needed, do a softclose to nicely shut down the command\n$exp->softclose();\n# or be less patient with\n$exp->hardclose();\nExpect.pm is built to either spawn a process or take an existing filehandle and interact with it\nsuch that normally interactive tasks can be done without operator assistance. This concept makes\nmore sense if you are already familiar with the versatile Tcl version of Expect. The public\nfunctions that make up Expect.pm are:\nExpect->new()\nExpect::interconnect(@objectstobereadfrom)\nExpect::testhandles($timeout, @objectstotest)\nExpect::version($versionrequested | undef);\n$object->spawn(@command)\n$object->clearaccum()\n$object->setaccum($value)\n$object->debug($debuglevel)\n$object->expinternal(0 | 1)\n$object->notransfer(0 | 1)\n$object->rawpty(0 | 1)\n$object->stty(@sttymodes) # See the IO::Stty docs\n$object->slave()\n$object->before();\n$object->match();\n$object->after();\n$object->matchlist();\n$object->matchnumber();\n$object->error();\n$object->command();\n$object->exitstatus();\n$object->ptyhandle();\n$object->dosoftclose();\n$object->restarttimeoutuponreceive(0 | 1);\n$object->interact($otherobject, $escapesequence)\n$object->loggroup(0 | 1 | undef)\n$object->loguser(0 | 1 | undef)\n$object->logfile(\"filename\" | $filehandle | \\&coderef | undef)\n$object->manualstty(0 | 1 | undef)\n$object->matchmax($maxbuffersize or undef)\n$object->pid();\n$object->sendslow($delay, @stringstosend)\n$object->setgroup(@listengroupobjects | undef)\n$object->setseq($sequence,\\&function,\\@parameters);\nThere are several configurable package variables that affect the behavior of Expect. They are:\n$Expect::Debug;\n$Expect::ExpInternal;\n$Expect::IgnoreEintr;\n$Expect::LogGroup;\n$Expect::LogStdout;\n$Expect::ManualStty;\n$Expect::MultilineMatching;\n$Expect::DoSoftClose;",
    "sections": {
        "NAME": {
            "content": "Expect.pm - Expect for Perl\n",
            "subsections": []
        },
        "VERSION": {
            "content": "1.21\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Expect;\n\n# create an Expect object by spawning another process\nmy $exp = Expect->spawn($command, @params)\nor die \"Cannot spawn $command: $!\\n\";\n\n# or by using an already opened filehandle (e.g. from Net::Telnet)\nmy $exp = Expect->expinit(\\*FILEHANDLE);\n\n# if you prefer the OO mindset:\nmy $exp = new Expect;\n$exp->rawpty(1);\n$exp->spawn($command, @parameters)\nor die \"Cannot spawn $command: $!\\n\";\n\n# send some string there:\n$exp->send(\"string\\n\");\n\n# or, for the filehandle mindset:\nprint $exp \"string\\n\";\n\n# then do some pattern matching with either the simple interface\n$patidx = $exp->expect($timeout, @matchpatterns);\n\n# or multi-match on several spawned commands with callbacks,\n# just like the Tcl version\n$exp->expect($timeout,\n[ qr/regex1/ => sub { my $exp = shift;\n$exp->send(\"response\\n\");\nexpcontinue; } ],\n[ \"regexp2\" , \\&callback, @cbparms ],\n);\n\n# if no longer needed, do a softclose to nicely shut down the command\n$exp->softclose();\n\n# or be less patient with\n$exp->hardclose();\n\nExpect.pm is built to either spawn a process or take an existing filehandle and interact with it\nsuch that normally interactive tasks can be done without operator assistance. This concept makes\nmore sense if you are already familiar with the versatile Tcl version of Expect. The public\nfunctions that make up Expect.pm are:\n\nExpect->new()\nExpect::interconnect(@objectstobereadfrom)\nExpect::testhandles($timeout, @objectstotest)\nExpect::version($versionrequested | undef);\n$object->spawn(@command)\n$object->clearaccum()\n$object->setaccum($value)\n$object->debug($debuglevel)\n$object->expinternal(0 | 1)\n$object->notransfer(0 | 1)\n$object->rawpty(0 | 1)\n$object->stty(@sttymodes) # See the IO::Stty docs\n$object->slave()\n$object->before();\n$object->match();\n$object->after();\n$object->matchlist();\n$object->matchnumber();\n$object->error();\n$object->command();\n$object->exitstatus();\n$object->ptyhandle();\n$object->dosoftclose();\n$object->restarttimeoutuponreceive(0 | 1);\n$object->interact($otherobject, $escapesequence)\n$object->loggroup(0 | 1 | undef)\n$object->loguser(0 | 1 | undef)\n$object->logfile(\"filename\" | $filehandle | \\&coderef | undef)\n$object->manualstty(0 | 1 | undef)\n$object->matchmax($maxbuffersize or undef)\n$object->pid();\n$object->sendslow($delay, @stringstosend)\n$object->setgroup(@listengroupobjects | undef)\n$object->setseq($sequence,\\&function,\\@parameters);\n\nThere are several configurable package variables that affect the behavior of Expect. They are:\n\n$Expect::Debug;\n$Expect::ExpInternal;\n$Expect::IgnoreEintr;\n$Expect::LogGroup;\n$Expect::LogStdout;\n$Expect::ManualStty;\n$Expect::MultilineMatching;\n$Expect::DoSoftClose;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The Expect module is a successor of Comm.pl and a descendent of Chat.pl. It more closely\nressembles the Tcl Expect language than its predecessors. It does not contain any of the\nnetworking code found in Comm.pl. I suspect this would be obsolete anyway given the advent of\nIO::Socket and external tools such as netcat.\n\nExpect.pm is an attempt to have more of a switch() & case feeling to make decision processing\nmore fluid. Three separate types of debugging have been implemented to make code production\neasier.\n\nIt is possible to interconnect multiple file handles (and processes) much like Tcl's Expect. An\nattempt was made to enable all the features of Tcl's Expect without forcing Tcl on the victim\nprogrammer :-) .\n\nPlease, before you consider using Expect, read the FAQs about \"I want to automate password entry\nfor su/ssh/scp/rsh/...\" and \"I want to use Expect to automate [anything with a buzzword]...\"\n",
            "subsections": []
        },
        "USAGE": {
            "content": "new Expect ()\nCreates a new Expect object, i.e. a pty. You can change parameters on it before actually\nspawning a command. This is important if you want to modify the terminal settings for the\nslave. See slave() below. The object returned is actually a reblessed IO::Pty filehandle, so\nsee there for additional methods.\n\nExpect->expinit(\\*FILEHANDLE) *or*\nExpect->init(\\*FILEHANDLE)\nInitializes $newhandleobject for use with other Expect functions. It must be passed a\nreference to FILEHANDLE if you want it to work properly. IO::File objects are preferable.\nReturns a reference to the newly created object.\n\nYou can use only real filehandles, certain tied filehandles (e.g. Net::SSH2) that lack a\nfileno() will not work. Net::Telnet objects can be used but have been reported to work only\nfor certain hosts. YMMV.\n\nExpect->spawn($command, @parameters) *or*\n$object->spawn($command, @parameters) *or*\nnew Expect ($command, @parameters)\nForks and execs $command. Returns an Expect object upon success or \"undef\" if the fork was\nunsuccessful or the command could not be found. spawn() passes its parameters unchanged to\nPerls exec(), so look there for detailed semantics.\n\nNote that if spawn cannot exec() the given command, the Expect object is still valid and the\nnext expect() will see \"Cannot exec\", so you can use that for error handling.\n\nAlso note that you cannot reuse an object with an already spawned command, even if that\ncommand has exited. Sorry, but you have to allocate a new object...\n\n$object->debug(0 | 1 | 2 | 3 | undef)\nSets debug level for $object. 1 refers to general debugging information, 2 refers to verbose\ndebugging and 0 refers to no debugging. If you call debug() with no parameters it will\nreturn the current debugging level. When the object is created the debugging level will\nmatch that $Expect::Debug, normally 0.\n\nThe '3' setting is new with 1.05, and adds the additional functionality of having the full\naccumulated buffer printed every time data is read from an Expect object. This was\nimplemented by request. I recommend against using this unless you think you need it as it\ncan create quite a quantity of output under some circumstances..\n\n$object->expinternal(1 | 0)\nSets/unsets 'expinternal' debugging. This is similar in nature to its Tcl counterpart. It\nis extremely valuable when debugging expect() sequences. When the object is created the\nexpinternal setting will match the value of $Expect::ExpInternal, normally 0. Returns the\ncurrent setting if called without parameters. It is highly recommended that you make use of\nthe debugging features lest you have angry code.\n\n$object->rawpty(1 | 0)\nSet pty to raw mode before spawning. This disables echoing, CR->LF translation and an ugly\nhack for broken Solaris TTYs (which send <space><backspace> to slow things down) and thus\ngives a more pipe-like behaviour (which is important if you want to transfer binary\ncontent). Note that this must be set *before* spawning the program.\n\n$object->stty(qw(mode1 mode2...))\nSets the tty mode for $object's associated terminal to the given modes. Note that on many\nsystems the master side of the pty is not a tty, so you have to modify the slave pty\ninstead, see next item. This needs IO::Stty installed, which is no longer required.\n\n$object->slave()\nReturns a filehandle to the slave part of the pty. Very useful in modifying the terminal\nsettings:\n\n$object->slave->stty(qw(raw -echo));\n\nTypical values are 'sane', 'raw', and 'raw -echo'. Note that I recommend setting the\nterminal to 'raw' or 'raw -echo', as this avoids a lot of hassle and gives pipe-like (i.e.\ntransparent) behaviour (without the buffering issue).\n\n$object->print(@strings) *or*\n$object->send(@strings)\nSends the given strings to the spawned command. Note that the strings are not logged in the\nlogfile (see printlogfile) but will probably be echoed back by the pty, depending on pty\nsettings (default is echo) and thus end up there anyway. This must also be taken into\naccount when expect()ing for an answer: the next string will be the command just sent. I\nsuggest setting the pty to raw, which disables echo and makes the pty transparently act like\na bidirectional pipe.\n\n$object->expect($timeout, @matchpatterns)\nor, more like Tcl/Expect,\n\nexpect($timeout,\n'-i', [ $obj1, $obj2, ... ],\n[ $repattern, sub { ...; expcontinue; }, @subparms, ],\n[ 'eof', sub { ... } ],\n[ 'timeout', sub { ... }, \\$subparm1 ],\n'-i', [ $objn, ...],\n'-ex', $exactpattern, sub { ... },\n$exactpattern, sub { ...; expcontinuetimeout; },\n'-re', $repattern, sub { ... },\n'-i', \\@objectlist, @patternlist,\n...);\n\n*Simple interface:*\n\nGiven $timeout in seconds Expect will wait for $object's handle to produce one of the\nmatchpatterns, which are matched exactly by default. If you want a regexp match, prefix the\npattern with '-re'.\n\nDue to o/s limitations $timeout should be a round number. If $timeout is 0 Expect will check\none time to see if $object's handle contains any of the matchpatterns. If $timeout is undef\nExpect will wait forever for a pattern to match.\n\nIf called in a scalar context, expect() will return the position of the matched pattern\nwithin $matchpatterns, or undef if no pattern was matched. This is a position starting from\n1, so if you want to know which of an array of @matchedpatterns matched you should subtract\none from the return value.\n\nIf called in an array context expect() will return ($matchedpatternposition, $error,\n$successfullymatchingstring, $beforematch, and $aftermatch).\n\n$matchedpatternposition will contain the value that would have been returned if expect()\nhad been called in a scalar context. $error is the error that occurred that caused expect()\nto return. $error will contain a number followed by a string equivalent expressing the\nnature of the error. Possible values are undef, indicating no error, '1:TIMEOUT' indicating\nthat $timeout seconds had elapsed without a match, '2:EOF' indicating an eof was read from\n$object, '3: spawn id($fileno) died' indicating that the process exited before matching and\n'4:$!' indicating whatever error was set in $ERRNO during the last read on $object's handle\nor during select(). All handles indicated by setgroup plus STDOUT will have all data to\ncome out of $object printed to them during expect() if loggroup and logstdout are set.\n\nChanged from older versions is the regular expression handling. By default now all strings\npassed to expect() are treated as literals. To match a regular expression pass '-re' as a\nparameter in front of the pattern you want to match as a regexp.\n\nExample:\n\n$object->expect(15, 'match me exactly','-re','match\\s+me\\s+exactly');\n\nThis change makes it possible to match literals and regular expressions in the same expect()\ncall.\n\nAlso new is multiline matching. ^ will now match the beginning of lines. Unfortunately,\nbecause perl doesn't use $/ in determining where lines break using $ to find the end of a\nline frequently doesn't work. This is because your terminal is returning \"\\r\\n\" at the end\nof every line. One way to check for a pattern at the end of a line would be to use \\r?$\ninstead of $.\n\nExample: Spawning telnet to a host, you might look for the escape character. telnet would\nreturn to you \"\\r\\nEscape character is '^]'.\\r\\n\". To find this you might use\n$match='^Escape char.*\\.\\r?$';\n\n$telnet->expect(10,'-re',$match);\n\n*New more Tcl/Expect-like interface:*\n\nIt's now possible to expect on more than one connection at a time by specifying '\"-i\"' and a\nsingle Expect object or a ref to an array containing Expect objects, e.g.\n\nexpect($timeout,\n'-i', $exp1, @patterns1,\n'-i', [ $exp2, $exp3 ], @patterns23,\n)\n\nFurthermore, patterns can now be specified as array refs containing [$regexp, sub { ...},\n@optionalsubprams] . When the pattern matches, the subroutine is called with parameters\n($matchedexpectobj, @optionalsubparms). The subroutine can return the symbol\n`expcontinue' to continue the expect matching with timeout starting anew or return the\nsymbol `expcontinuetimeout' for continuing expect without resetting the timeout count.\n\n$exp->expect($timeout,\n[ qr/username: /i, sub { my $self = shift;\n$self->send(\"$username\\n\");\nexpcontinue; }],\n[ qr/password: /i, sub { my $self = shift;\n$self->send(\"$password\\n\");\nexpcontinue; }],\n$shellprompt);\n\n`expect' is now exported by default.\n\n$object->expbefore() *or*\n$object->before()\nbefore() returns the 'before' part of the last expect() call. If the last expect() call\ndidn't match anything, expbefore() will return the entire output of the object accumulated\nbefore the expect() call finished.\n\nNote that this is something different than Tcl Expects before()!!\n\n$object->expafter() *or*\n$object->after()\nreturns the 'after' part of the last expect() call. If the last expect() call didn't match\nanything, expafter() will return undef().\n\n$object->expmatch() *or*\n$object->match()\nreturns the string matched by the last expect() call, undef if no string was matched.\n\n$object->expmatchnumber() *or*\n$object->matchnumber()\nexpmatchnumber() returns the number of the pattern matched by the last expect() call. Keep\nin mind that the first pattern in a list of patterns is 1, not 0. Returns undef if no\npattern was matched.\n\n$object->expmatchlist() *or*\n$object->matchlist()\nexpmatchlist() returns a list of matched substrings from the brackets () inside the regexp\nthat last matched. ($object->matchlist)[0] thus corresponds to $1, ($object->matchlist)[1]\nto $2, etc.\n\n$object->experror() *or*\n$object->error()\nexperror() returns the error generated by the last expect() call if no pattern was matched.\nIt is typically useful to examine the value returned by before() to find out what the output\nof the object was in determining why it didn't match any of the patterns.\n\n$object->clearaccum()\nClear the contents of the accumulator for $object. This gets rid of any residual contents of\na handle after expect() or sendslow() such that the next expect() call will only see new\ndata from $object. The contents of the accumulator are returned.\n\n$object->setaccum($value)\nSets the content of the accumulator for $object to $value. The previous content of the\naccumulator is returned.\n\n$object->expcommand() *or*\n$object->command()\nexpcommand() returns the string that was used to spawn the command. Helpful for debugging\nand for reused patternmatch subroutines.\n\n$object->expexitstatus() *or*\n$object->exitstatus()\nReturns the exit status of $object (if it already exited).\n\n$object->expptyhandle() *or*\n$object->ptyhandle()\nReturns a string representation of the attached pty, for example: `spawn id(5)' (pty has\nfileno 5), `handle id(7)' (pty was initialized from fileno 7) or `STDIN'. Useful for\ndebugging.\n\n$object->restarttimeoutuponreceive(0 | 1)\nIf this is set to 1, the expect timeout is retriggered whenever something is received from\nthe spawned command. This allows to perform some aliveness testing and still expect for\npatterns.\n\n$exp->restarttimeoutuponreceive(1);\n$exp->expect($timeout,\n[ timeout => \\&reporttimeout ],\n[ qr/pattern/ => \\&handlepattern],\n);\n\nNow the timeout isn't triggered if the command produces any kind of output, i.e. is still\nalive, but you can act upon patterns in the output.\n\n$object->notransfer(1 | 0)\nDo not truncate the content of the accumulator after a match. Normally, the accumulator is\nset to the remains that come after the matched string. Note that this setting is per object\nand not per pattern, so if you want to have normal acting patterns that truncate the\naccumulator, you have to add a\n\n$exp->setaccum($exp->after);\n\nto their callback, e.g.\n\n$exp->notransfer(1);\n$exp->expect($timeout,\n# accumulator not truncated, pattern1 will match again\n[ \"pattern1\" => sub { my $self = shift;\n...\n} ],\n# accumulator truncated, pattern2 will not match again\n[ \"pattern2\" => sub { my $self = shift;\n...\n$self->setaccum($self->after());\n} ],\n);\n\nThis is only a temporary fix until I can rewrite the pattern matching part so it can take\nthat additional -notransfer argument.\n\nExpect::interconnect(@objects);\nRead from @objects and print to their @listengroups until an escape sequence is matched\nfrom one of @objects and the associated function returns 0 or undef. The special escape\nsequence 'EOF' is matched when an object's handle returns an end of file. Note that it is\nnot necessary to include objects that only accept data in @objects since the escape sequence\nis read from an object. Further note that the listengroup for a write-only object is\nalways empty. Why would you want to have objects listening to STDOUT (for example)? By\ndefault every member of @objects as well as every member of its listen group will be set\nto 'raw -echo' for the duration of interconnection. Setting $object->manualstty() will stop\nthis behavior per object. The original tty settings will be restored as interconnect exits.\n\nFor a generic way to interconnect processes, take a look at IPC::Run.\n\nExpect::testhandles($timeout, @objects)\nGiven a set of objects determines which objects' handles have data ready to be read. Returns\nan array who's members are positions in @objects that have ready handles. Returns undef if\nthere are no such handles ready.\n\nExpect::version($versionrequested or undef);\nReturns current version of Expect. As of .99 earlier versions are not supported. Too many\nthings were changed to make versioning possible.\n\n$object->interact( \"\\*FILEHANDLE, $escapesequence\")\ninteract() is essentially a macro for calling interconnect() for connecting 2 processes\ntogether. \\*FILEHANDLE defaults to \\*STDIN and $escapesequence defaults to undef.\nInteraction ceases when $escapesequence is read from FILEHANDLE, not $object. $object's\nlisten group will consist solely of \\*FILEHANDLE for the duration of the interaction.\n\\*FILEHANDLE will not be echoed on STDOUT.\n\n$object->loggroup(0 | 1 | undef)\nSet/unset logging of $object to its 'listen group'. If set all objects in the listen group\nwill have output from $object printed to them during $object->expect(),\n$object->sendslow(), and \"Expect::interconnect($object , ...)\". Default value is on. During\ncreation of $object the setting will match the value of $Expect::LogGroup, normally 1.\n\n$object->loguser(0 | 1 | undef) *or*\n$object->logstdout(0 | 1 | undef)\nSet/unset logging of object's handle to STDOUT. This corresponds to Tcl's loguser variable.\nReturns current setting if called without parameters. Default setting is off for initialized\nhandles. When a process object is created (not a filehandle initialized with expinit) the\nlogstdout setting will match the value of $Expect::LogStdout variable, normally 1. If/when\nyou initialize STDIN it is usually associated with a tty which will by default echo to\nSTDOUT anyway, so be careful or you will have multiple echoes.\n\n$object->logfile(\"filename\" | $filehandle | \\&coderef | undef)\nLog session to a file. All characters send to or received from the spawned process are\nwritten to the file. Normally appends to the logfile, but you can pass an additional mode of\n\"w\" to truncate the file upon open():\n\n$object->logfile(\"filename\", \"w\");\n\nReturns the logfilehandle.\n\nIf called with an undef value, stops logging and closes logfile:\n\n$object->logfile(undef);\n\nIf called without argument, returns the logfilehandle:\n\n$fh = $object->logfile();\n\nCan be set to a code ref, which will be called instead of printing to the logfile:\n\n$object->logfile(\\&myloggerfunc);\n\n$object->printlogfile(@strings)\nPrints to logfile (if opened) or calls the logfile hook function. This allows the user to\nadd arbitraty text to the logfile. Note that this could also be done as\n$object->logfile->print() but would only work for log files, not code hooks.\n\n$object->setseq($sequence, \\&function, \\@functionparameters)\nDuring Expect->interconnect() if $sequence is read from $object &function will be executed\nwith parameters @functionparameters. It is highly recommended that the escape sequence be\na single character since the likelihood is great that the sequence will be broken into to\nseparate reads from the $object's handle, making it impossible to strip $sequence from\ngetting printed to $object's listen group. \\&function should be something like\n'main::controlwfunction' and @functionparameters should be an array defined by the\ncaller, passed by reference to setseq(). Your function should return a non-zero value if\nexecution of interconnect() is to resume after the function returns, zero or undefined if\ninterconnect() should return after your function returns. The special sequence 'EOF' matches\nthe end of file being reached by $object. See interconnect() for details.\n\n$object->setgroup(@listenerobjects)\n@listenerobjects is the list of objects that should have their handles printed to by\n$object when Expect::interconnect, $object->expect() or $object->sendslow() are called.\nCalling w/out parameters will return the current list of the listener objects.\n\n$object->manualstty(0 | 1 | undef)\nSets/unsets whether or not Expect should make reasonable guesses as to when and how to set\ntty parameters for $object. Will match $Expect::ManualStty value (normally 0) when $object\nis created. If called without parameters manualstty() will return the current manualstty\nsetting.\n\n$object->matchmax($maximumbufferlength | undef) *or*\n$object->maxaccum($maximumbufferlength | undef)\nSet the maximum accumulator size for object. This is useful if you think that the\naccumulator will grow out of hand during expect() calls. Since the buffer will be matched by\nevery matchpattern it may get slow if the buffer gets too large. Returns current value if\ncalled without parameters. Not defined by default.\n\n$object->notransfer(0 | 1)\nIf set, matched strings will not be deleted from the accumulator. Returns current value if\ncalled without parameters. False by default.\n\n$object->exppid() *or*\n$object->pid()\nReturn pid of $object, if one exists. Initialized filehandles will not have pids (of\ncourse).\n\n$object->sendslow($delay, @strings);\nprint each character from each string of @strings one at a time with $delay seconds before\neach character. This is handy for devices such as modems that can be annoying if you send\nthem data too fast. After each character $object will be checked to determine whether or not\nit has any new data ready and if so update the accumulator for future expect() calls and\nprint the output to STDOUT and @listengroup if logstdout and loggroup are appropriately\nset.\n",
            "subsections": [
                {
                    "name": "Configurable Package Variables:",
                    "content": "$Expect::Debug\nDefaults to 0. Newly created objects have a $object->debug() value of $Expect::Debug. See\n$object->debug();\n\n$Expect::DoSoftClose\nDefaults to 0. When destroying objects, softclose may take up to half a minute to shut\neverything down. From now on, only hardclose will be called, which is less polite but still\ngives the process a chance to terminate properly. Set this to '1' for old behaviour.\n\n$Expect::ExpInternal\nDefaults to 0. Newly created objects have a $object->expinternal() value of\n$Expect::ExpInternal. See $object->expinternal().\n\n$Expect::IgnoreEintr\nDefaults to 0. If set to 1, when waiting for new data, Expect will ignore EINTR errors and\nrestart the select() call instead.\n\n$Expect::LogGroup\nDefaults to 1. Newly created objects have a $object->loggroup() value of\n$Expect::LogGroup. See $object->loggroup().\n\n$Expect::LogStdout\nDefaults to 1 for spawned commands, 0 for file handles attached with expinit(). Newly\ncreated objects have a $object->logstdout() value of $Expect::LogStdout. See\n$object->logstdout().\n\n$Expect::ManualStty\nDefaults to 0. Newly created objects have a $object->manualstty() value of\n$Expect::ManualStty. See $object->manualstty().\n\n$Expect::MultilineMatching\nDefaults to 1. Affects whether or not expect() uses the /m flag for\ndoing regular expression matching. If set to 1 /m is used.\nThis makes a difference when you are trying to match ^ and $. If\nyou have this on you can match lines in the middle of a page of output\nusing ^ and $ instead of it matching the beginning and end of the entire\nexpression. I think this is handy.\n"
                }
            ]
        },
        "CONTRIBUTIONS": {
            "content": "Lee Eakin <leakin@japh.itg.ti.com> has ported the kibitz script from Tcl/Expect to Perl/Expect.\n\nJeff Carr <jcarr@linuxmachines.com> provided a simple example of how handle terminal window\nresize events (transmitted via the WINCH signal) in a ssh session.\n\nYou can find both scripts in the examples/ subdir. Thanks to both!\n\nHistorical notes:\n\nThere are still a few lines of code dating back to the inspirational Comm.pl and Chat.pl modules\nwithout which this would not have been possible. Kudos to Eric Arnold <Eric.Arnold@Sun.com> and\nRandal 'Nuke your NT box with one line of perl code' Schwartz<merlyn@stonehenge.com> for making\nthese available to the perl public.\n\nAs of .98 I think all the old code is toast. No way could this have been done without it though.\nSpecial thanks to Graham Barr for helping make sense of the IO::Handle stuff as well as\nproviding the highly recommended IO::Tty module.\n",
            "subsections": []
        },
        "REFERENCES": {
            "content": "Mark Rogaski <rogaski@att.com> wrote:\n\n\"I figured that you'd like to know that Expect.pm has been very useful to AT&T Labs over the\npast couple of years (since I first talked to Austin about design decisions). We use Expect.pm\nfor managing the switches in our network via the telnet interface, and such automation has\nsignificantly increased our reliability. So, you can honestly say that one of the largest\ndigital networks in existence (AT&T Frame Relay) uses Expect.pm quite extensively.\"\n\nFAQ - Frequently Asked Questions\nThis is a growing collection of things that might help. Please send you questions that are not\nanswered here to RGiersig@cpan.org\n\nWhat systems does Expect run on?\nExpect itself doesn't have real system dependencies, but the underlying IO::Tty needs\npseudoterminals. IO::Stty uses POSIX.pm and Fcntl.pm.\n\nI have used it on Solaris, Linux and AIX, others report *BSD and OSF as working. Generally, any\nmodern POSIX Unix should do, but there are exceptions to every rule. Feedback is appreciated.\n\nSee IO::Tty for a list of verified systems.\n\nCan I use this module with ActivePerl on Windows?\nUp to now, the answer was 'No', but this has changed.\n\nYou still cannot use ActivePerl, but if you use the Cygwin environment\n(http://sources.redhat.com), which brings its own perl, and have the latest IO::Tty (v0.05 or\nlater) installed, it should work (feedback appreciated).\n\nThe examples in the tutorial don't work!\nThe tutorial is hopelessly out of date and needs a serious overhaul. I appologize for this, I\nhave concentrated my efforts mainly on the functionality. Volunteers welcomed.\n\nHow can I find out what Expect is doing?\nIf you set\n\n$Expect::ExpInternal = 1;\n\nExpect will tell you very verbosely what it is receiving and sending, what matching it is trying\nand what it found. You can do this on a per-command base with\n\n$exp->expinternal(1);\n\nYou can also set\n\n$Expect::Debug = 1;  # or 2, 3 for more verbose output\n\nor\n\n$exp->debug(1);\n\nwhich gives you even more output.\n\nI am seeing the output of the command I spawned.  Can I turn that off?\nYes, just set\n\n$Expect::LogStdout = 0;\n\nto globally disable it or\n\n$exp->logstdout(0);\n\nfor just that command. 'loguser' is provided as an alias so Tcl/Expect user get a DWIM\nexperience... :-)\n",
            "subsections": [
                {
                    "name": "No, I mean that when I send some text to the spawned process, it gets echoed back and I have to deal with it in the next expect.",
                    "content": "This is caused by the pty, which has probably 'echo' enabled. A solution would be to set the pty\nto raw mode, which in general is cleaner for communication between two programs (no more\nunexpected character translations). Unfortunately this would break a lot of old code that sends\n\"\\r\" to the program instead of \"\\n\" (translating this is also handled by the pty), so I won't\nadd this to Expect just like that. But feel free to experiment with \"$exp->rawpty(1)\".\n\nHow do I send control characters to a process?\nA: You can send any characters to a process with the print command. To represent a control\ncharacter in Perl, use \\c followed by the letter. For example, control-G can be represented with\n\"\\cG\" . Note that this will not work if you single-quote your string. So, to send control-C to a\nprocess in $exp, do:\n\nprint $exp \"\\cC\";\n\nOr, if you prefer:\n\n$exp->send(\"\\cC\");\n\nThe ability to include control characters in a string like this is provided by Perl, not by\nExpect.pm . Trying to learn Expect.pm without a thorough grounding in Perl can be very daunting.\nWe suggest you look into some of the excellent Perl learning material, such as the books\nProgramming Perl and Learning Perl by O'Reilly, as well as the extensive online Perl\ndocumentation available through the perldoc command.\n"
                },
                {
                    "name": "My script fails from time to time without any obvious reason.  It seems that I am sometimes loosing output from the spawned program.",
                    "content": "You could be exiting too fast without giving the spawned program enough time to finish. Try\nadding $exp->softclose() to terminate the program gracefully or do an expect() for 'eof'.\n\nAlternatively, try adding a 'sleep 1' after you spawn() the program. It could be that pty\ncreation on your system is just slow (but this is rather improbable if you are using the latest\nIO-Tty).\n\nI want to automate password entry for su/ssh/scp/rsh/...\nYou shouldn't use Expect for this. Putting passwords, especially root passwords, into scripts in\nclear text can mean severe security problems. I strongly recommend using other means. For 'su',\nconsider switching to 'sudo', which gives you root access on a per-command and per-user basis\nwithout the need to enter passwords. 'ssh'/'scp' can be set up with RSA authentication without\npasswords. 'rsh' can use the .rhost mechanism, but I'd strongly suggest to switch to 'ssh'; to\nmention 'rsh' and 'security' in the same sentence makes an oxymoron.\n\nIt will work for 'telnet', though, and there are valid uses for it, but you still might want to\nconsider using 'ssh', as keeping cleartext passwords around is very insecure.\n\nI want to use Expect to automate [anything with a buzzword]...\nAre you sure there is no other, easier way? As a rule of thumb, Expect is useful for automating\nthings that expect to talk to a human, where no formal standard applies. For other tasks that do\nfollow a well-defined protocol, there are often better-suited modules that already can handle\nthose protocols. Don't try to do HTTP requests by spawning telnet to port 80, use LWP instead.\nTo automate FTP, take a look at Net::FTP or \"ncftp\" (http://www.ncftp.org). You don't use a\nscrewdriver to hammer in your nails either, or do you?\n\nIs it possible to use threads with Expect?\nBasically yes, with one restriction: you must spawn() your programs in the main thread and then\npass the Expect objects to the handling threads. The reason is that spawn() uses fork(), and\nperlthrtut:\n\n\"Thinking of mixing fork() and threads?  Please lie down and wait until the feeling passes.\"\n\nI want to log the whole session to a file.\nUse\n\n$exp->logfile(\"filename\");\n\nor\n\n$exp->logfile($filehandle);\n\nor even\n\n$exp->logfile(\\&logprocedure);\n\nfor maximum flexibility.\n\nNote that the logfile is appended to by default, but you can specify an optional mode \"w\" to\ntruncate the logfile:\n\n$exp->logfile(\"filename\", \"w\");\n\nTo stop logging, just call it with a false argument:\n\n$exp->logfile(undef);\n\nHow can I turn off multi-line matching for my regexps?\nTo globally unset multi-line matching for all regexps:\n\n$Expect::MultilineMatching = 0;\n\nYou can do that on a per-regexp basis by stating \"(?-m)\" inside the regexp (you need perl5.00503\nor later for that).\n\nHow can I expect on multiple spawned commands?\nYou can use the -i parameter to specify a single object or a list of Expect objects. All\nfollowing patterns will be evaluated against that list.\n\nYou can specify -i multiple times to create groups of objects and patterns to match against\nwithin the same expect statement.\n\nThis works just like in Tcl/Expect.\n\nSee the source example below.\n\nI seem to have problems with ptys!\nWell, pty handling is really a black magic, as it is extremely system dependend. I have\nextensively revised IO-Tty, so these problems should be gone.\n\nIf your system is listed in the \"verified\" list of IO::Tty, you probably have some non-standard\nsetup, e.g. you compiled your Linux-kernel yourself and disabled ptys. Please ask your friendly\nsysadmin for help.\n\nIf your system is not listed, unpack the latest version of IO::Tty, do a 'perl Makefile.PL;\nmake; make test; uname \"-a\"' and send me the results and I'll see what I can deduce from that.\n\nI just want to read the output of a process without expect()ing anything. How can I do this?\n[ Are you sure you need Expect for this? How about qx() or open(\"prog|\")? ]\n\nBy using expect without any patterns to match.\n\n$process->expect(undef); # Forever until EOF\n$process->expect($timeout); # For a few seconds\n$process->expect(0); # Is there anything ready on the handle now?\n\nOk, so now how do I get what was read on the handle?\n$read = $process->before();\n\nWhere's IO::Pty?\nFind it on CPAN as IO-Tty, which provides both.\n\nHow come when I automate the passwd program to change passwords for me passwd dies before changing the password sometimes/every time?\nWhat's happening is you are closing the handle before passwd exits. When you close the handle to\na process, it is sent a signal (SIGPIPE?) telling it that STDOUT has gone away. The default\nbehavior for processes is to die in this circumstance. Two ways you can make this not happen\nare:\n\n$process->softclose();\n\nThis will wait 15 seconds for a process to come up with an EOF by itself before killing it.\n\n$process->expect(undef);\n\nThis will wait forever for the process to match an empty set of patterns. It will return when\nthe process hits an EOF.\n\nAs a rule, you should always expect() the result of your transaction before you continue with\nprocessing.\n\nHow come when I try to make a logfile with logfile() or setgroup() it doesn't print anything after the last time I run expect()?\nOutput is only printed to the logfile/group when Expect reads from the process, during expect(),"
                },
                {
                    "name": "send_slow",
                    "content": "$process->expect(undef);\n\nand\n\n$process->expect(0);\n\nwhich will make expect() run with an empty pattern set forever or just for an instant to capture\nthe output of $process. The output is available in the accumulator, so you can grab it using\n$process->before().\n\nI seem to have problems with terminal settings, double echoing, etc.\nTty settings are a major pain to keep track of. If you find unexpected behavior such as\ndouble-echoing or a frozen session, doublecheck the documentation for default settings. When in\ndoubt, handle them yourself using $exp->stty() and manualstty() functions. As of .98 you\nshouldn't have to worry about stty settings getting fouled unless you use interconnect or\nintentionally change them (like doing -echo to get a password).\n\nIf you foul up your terminal's tty settings, kill any hung processes and enter 'stty sane' at a\nshell prompt. This should make your terminal manageable again.\n\nNote that IO::Tty returns ptys with your systems default setting regarding echoing, CRLF\ntranslation etc. and Expect does not change them. I have considered setting the ptys to 'raw'\nwithout any translation whatsoever, but this would break a lot of existing things, as '\\r'\ntranslation would not work anymore. On the other hand, a raw pty works much like a pipe and is\nmore WYGIWYE (what you get is what you expect), so I suggest you set it to 'raw' by yourself:\n\n$exp = new Expect;\n$exp->rawpty(1);\n$exp->spawn(...);\n\nTo disable echo:\n\n$exp->slave->stty(qw(-echo));\n\nI'm spawning a telnet/ssh session and then let the user interact with it.  But screen-oriented applications on the other side don't work properly.\nYou have to set the terminal screen size for that. Luckily, IO::Pty already has a method for\nthat, so modify your code to look like this:\n\nmy $exp = new Expect;\n$exp->slave->clonewinsizefrom(\\*STDIN);\n$exp->spawn(\"telnet somehost);\n\nAlso, some applications need the TERM shell variable set so they know how to move the cursor\nacross the screen. When logging in, the remote shell sends a query (Ctrl-Z I think) and expects\nthe terminal to answer with a string, e.g. 'xterm'. If you really want to go that way (be aware,\nmadness lies at its end), you can handle that and send back the value in $ENV{TERM}. This is\nonly a hand-waving explanation, please figure out the details by yourself.\n\nI set the terminal size as explained above, but if I resize the window, the application does not notice this.\nYou have to catch the signal WINCH (\"window size changed\"), change the terminal size and\npropagate the signal to the spawned application:\n\nmy $exp = new Expect;\n$exp->slave->clonewinsizefrom(\\*STDIN);\n$exp->spawn(\"ssh somehost);\n$SIG{WINCH} = \\&winch;\n\nsub winch {\n$exp->slave->clonewinsizefrom(\\*STDIN);\nkill WINCH => $exp->pid if $exp->pid;\n$SIG{WINCH} = \\&winch;\n}\n\n$exp->interact();\n\nThere is an example file ssh.pl in the examples/ subdir that shows how this works with ssh.\nPlease note that I do strongly object against using Expect to automate ssh login, as there are\nbetter way to do that (see ssh-keygen).\n\nI noticed that the test uses a string that resembles, but not exactly matches, a well-known sentence that contains every character.  What does that mean?\nThat means you are anal-retentive. :-) [Gotcha there!]\n\nI get a \"Could not assign a pty\" error when running as a non-root user on an IRIX box?\nThe OS may not be configured to grant additional pty's (pseudo terminals) to non-root users.\n/usr/sbin/mkpts should be 4755, not 700 for this to work. I don't know about security\nimplications if you do this.\n\nHow come I don't notice when the spawned process closes its stdin/out/err??\nYou are probably on one of the systems where the master doesn't get an EOF when the slave closes\nstdin/out/err.\n\nOne possible solution is when you spawn a process, follow it with a unique string that would\nindicate the process is finished.\n\n$process = Expect->spawn('telnet somehost; echo END');\n\nAnd then $process->expect($timeout,'END','other','patterns');\n"
                }
            ]
        },
        "Source Examples": {
            "content": "",
            "subsections": [
                {
                    "name": "How to automate login",
                    "content": "my $telnet = new Net::Telnet (\"remotehost\") # see Net::Telnet\nor die \"Cannot telnet to remotehost: $!\\n\";;\nmy $exp = Expect->expinit($telnet);\n\n# deprecated use of spawned telnet command\n# my $exp = Expect->spawn(\"telnet localhost\")\n#   or die \"Cannot spawn telnet: $!\\n\";;\n\nmy $spawnok;\n$exp->expect($timeout,\n[\nqr'login: $',\nsub {\n$spawnok = 1;\nmy $fh = shift;\n$fh->send(\"$username\\n\");\nexpcontinue;\n}\n],\n[\n'Password: $',\nsub {\nmy $fh = shift;\nprint $fh \"$password\\n\";\nexpcontinue;\n}\n],\n[\neof =>\nsub {\nif ($spawnok) {\ndie \"ERROR: premature EOF in login.\\n\";\n} else {\ndie \"ERROR: could not spawn telnet.\\n\";\n}\n}\n],\n[\ntimeout =>\nsub {\ndie \"No login.\\n\";\n}\n],\n'-re', qr'[#>:] $', #' wait for shell prompt, then exit expect\n);\n"
                },
                {
                    "name": "How to expect on multiple spawned commands",
                    "content": "foreach my $cmd (@listofcommands) {\npush @commands, Expect->spawn($cmd);\n}\n\nexpect($timeout,\n'-i', \\@commands,\n[\nqr\"pattern\",          # find this pattern in output of all commands\nsub {\nmy $obj = shift;    # object that matched\nprint $obj \"something\\n\";\nexpcontinue;       # we don't want to terminate the expect call\n}\n],\n'-i', $someothercommand,\n[\n\"some other pattern\",\nsub {\nmy ($obj, $parmref) = @;\n# ...\n\n# now we exit the expect command\n},\n\\$parm\n],\n);\n"
                },
                {
                    "name": "How to propagate terminal sizes",
                    "content": "my $exp = new Expect;\n$exp->slave->clonewinsizefrom(\\*STDIN);\n$exp->spawn(\"ssh somehost);\n$SIG{WINCH} = \\&winch;\n\nsub winch {\n$exp->slave->clonewinsizefrom(\\*STDIN);\nkill WINCH => $exp->pid if $exp->pid;\n$SIG{WINCH} = \\&winch;\n}\n\n$exp->interact();\n"
                }
            ]
        },
        "HOMEPAGE": {
            "content": "http://sourceforge.net/projects/expectperl/\n",
            "subsections": []
        },
        "MAILING LISTS": {
            "content": "There are two mailing lists available, expectperl-announce and expectperl-discuss, at\n\nhttp://lists.sourceforge.net/lists/listinfo/expectperl-announce\n\nand\n\nhttp://lists.sourceforge.net/lists/listinfo/expectperl-discuss\n",
            "subsections": []
        },
        "BUG TRACKING": {
            "content": "You can use the CPAN Request Tracker http://rt.cpan.org/ and submit new bugs under\n\nhttp://rt.cpan.org/Ticket/Create.html?Queue=Expect\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "(c) 1997 Austin Schutz <ASchutz@users.sourceforge.net> (retired)\n",
            "subsections": [
                {
                    "name": "expect",
                    "content": "This module is now maintained by Roland Giersig <RGiersig@cpan.org>\n"
                }
            ]
        },
        "LICENSE": {
            "content": "This module can be used under the same terms as Perl.\n",
            "subsections": []
        },
        "DISCLAIMER": {
            "content": "THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\nTHE POSSIBILITY OF SUCH DAMAGE.\n\nIn other words: Use at your own risk. Provided as is. Your mileage may vary. Read the source,\nLuke!\n\nAnd finally, just to be sure:\n\nAny Use of This Product, in Any Manner Whatsoever, Will Increase the Amount of Disorder in the\nUniverse. Although No Liability Is Implied Herein, the Consumer Is Warned That This Process Will\nUltimately Lead to the Heat Death of the Universe.\n",
            "subsections": []
        }
    },
    "summary": "Expect.pm - Expect for Perl",
    "flags": [],
    "examples": [],
    "see_also": []
}