while ( my $line = <$pipe> ) { push @cmd, $line; if ( $line =~ m/password prompt:/ ) { # define your pattern for the password prompt # maybe empty or reset @cmd last; # end while loop } } close $pipe;