A perfect use-case for closures!

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.)


In reply to Re: abstract expect call by smls
in thread abstract expect call by georgecarlin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.