 <p>Maybe you need to use <code>exp_continue</code> like-</p> <pre><code>use Expect; ... ... foreach my $cmd (@cmd_array){ $exp-&gt;expect(3, [ qr/($|#)/ =&gt; sub { shift-&gt;send("$cmd\n"); exp_continue;}] ); } </code></pre> <p>Also, i think the statements inside <code>sub{...}</code> runs only if pattern matches as per <code>qr/($|#)/</code>. Also, I would think that after you type in an input or command you would generally press the return key to execute the command hence the <code>$cmd\n</code>.</p>