in reply to abstract expect call
You can use a loop to dynamically generate the callback subs passed to expect():
my @actions = ( [qr/pattern1/, "response1", sub { dostuff.. } ], [qr/pattern2/, "response2", sub { do_other_stuff.. }], [qr/pattern3/, "response3", sub { do_this_stuff.. } ], ); $exp->expect($timeout, map { my ($pattern, $response, $code) = @$_; [ $pattern, sub { select(undef, undef, undef, 0.25); $exp->send($response); $code->(); } ]; } @actions);
In Perl, every subroutine which uses lexical variables that were declared outside of it, will use the version of those variables from the time the sub was created. The technical way of saying it, is that the subroutine becomes a "closure" - for an in-depth explanation see e.g. Closure on Closures.
So in this case, each copy of the "sub {...}" callback created inside the "map {...}" loop, will remember the corresponding values of $response and $code.
Update: If you want, you can replace $code->(); with goto &$code; to avoid the nested function call, and thus gain a tiny performance increase. The down-side is that you must remember not to add any additional commands to the closure after that line, because the goto will never return. (See the bottom two paragraphs of goto for an explanation.)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: abstract expect call
by georgecarlin (Acolyte) on Oct 28, 2013 at 10:21 UTC |