I have a subroutine that creates an SSH connection to a specified server using Expect. My subroutine is huge and ugly due to the fact that I have so many nested if-elsif-else statements. I am wondering what may be a better way to do this. Modified (for length) code below (notice all the nested if statements under if ( $match_num == 2 ) ):
sub connect { my $host = shift; my $SSH = Expect->spawn( @ssh, "$user\@$host" ); ( $match_num, $error, $match, $before, $after ) = $SSH->expect( $time, '-re', '[Nn]ew [Pp]assword:', '-re', '^[Pp]assword.*:', '-re', $prompt ); if ($match_num == 1) { $result = "FAILED: Account Expired"; } elsif ( $match_num == 2 ) { print $SSH "$pass\r"; ( $match_num, $error, $match, $before, $after ) = $SSH->expect( $time, '-re', '[Pp]assword.*:', '-re', $prompt ); if ( $match_num == 1) { $result = "FAILED: Incorrect Password"; } elsif ( $match_num == 2 ) { print $SSH "export PS1='scripts: '\r"; ( $match_num, $error, $match, $before, $after ) = $SSH->expect( $time, '-re', '\r\nscripts: ' ); if ( $match_num == 1 ) { $result = "SUCCESS: you are logged into $host"; } else { $before =~ s/\r\n//g; $after =~ s/\r\n//g; $result = "ERROR: $error BEFORE: $before AFTER: $af +ter"; } } elsif ( $match_num == 3) { $result = "SUCCESS: you are logged into $host"; } } elsif ( $match_num == 3) { $result = "SUCCESS: you are logged into $host"; } else { $before =~ s/\r\n//g; $after =~ s/\r\n//g; $result = "ERROR: $error BEFORE: $before AFTER: $after"; } }

In reply to Fixing cascading if-elsif-else statements by walkingthecow

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.