pablor has asked for the wisdom of the Perl Monks concerning the following question:

I am using Net::SSH::Expect to connect to a list of access points.

In some cases the connection dies and my script gets interrupted. I want the script to skip the AP but continue with the following ones, but the script dies

my $sshap = Net::SSH::Expect->new ( host => $apip, user => 'Cisco', ssh_option => '-o StrictHostKeyChecking=no', raw_pty => 1, timeout => 5 ); if($sshap->run_ssh()){ $sshap->waitfor ('Password:', 7) or warn "SSH problem: 'Password' +not found after 7 second"; $sshap->send ('Cisco'); $sshap->waitfor ("$ap\>", 3) or warn "SSH problem: $ap\> not found + after 3 second"; $sshap->send ('en'); $sshap->waitfor ('Password:', 3) or warn "SSH problem: 'EN Passwor +d' not found after 3 second"; $sshap->send ('Cisco'); $sshap->waitfor ("$ap\#", 3) or warn "SSH problem: $ap\# not found + after 3 second"; $sshap->send ('show ip interface brief'); while (defined ($line = $sshap->read_line()) ) { print "$line\n" } $sshap->send('exit'); $sshap->close(); } else { print "$apname Could not open SSH\n"; }

I found that I can handle that by using eval{}

Is that the best approach?

it seems that is running much slower when I use eval.

Replies are listed 'Best First'.
Re: Handling Exceptions on Net::SSH::Expect
by kcott (Archbishop) on Jan 16, 2017 at 21:58 UTC

    G'day pablor,

    Welcome to the Monastery.

    "I found that I can handle that by using eval{} Is that the best approach?"

    I find Try::Tiny can be a better approach. It's DESCRIPTION starts:

    "This module provides bare bones try/catch/finally statements that are designed to minimize common mistakes with eval blocks, and NOTHING else."

    Using eval can have some issues. See the BACKGROUND section of Try::Tiny for a discussion of these issues. As you haven't shown how you're using eval, I can't say whether any of those issues apply to you.

    There's lots of similar modules available, for instance, try CPAN Search for Try::.

    "it seems that is running much slower when I use eval." [my emphasis]

    Use Benchmark to compare speeds. I recommend running it several times; five is usual for me.

    — Ken