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

Greetings,

I'm creating a ssh wrapper but my while loop doesn't exit immediately. Is it possible to change this behavior?

Thanks

while() { print "enter cmd: "; chomp(my $c=<STDIN>); if ($c eq "") { # only exits after two enters??? last; } else { system("ssh somebox \"$c\""); } } #back to some other stuff

Replies are listed 'Best First'.
Re: System call to ssh stalling.
by JavaFan (Canon) on Jan 15, 2012 at 16:04 UTC
    Why would you expect the loop to exit immediately? The only way to escape the loop is via last, of which you have only one. And that is only encountered if you hit return after being prompted "enter cmd:".
Re: System call to ssh stalling.
by Khen1950fx (Canon) on Jan 15, 2012 at 14:53 UTC
    This worked for me.
    #!/usr/bin/perl use strict; use warnings; while (1) { print "enter cmd: "; unless (my $c = <STDIN>) { last; } else { system( "ssh 127.0.0.1 $c" ); last; } }
Re: System call to ssh stalling.
by Marshall (Canon) on Jan 16, 2012 at 00:48 UTC
    I prefer not to use while(1) type loops for anything other than say in a server loop. For a command loop I prefer to put the prompt and the exit condition test right there in the loop conditional. You can modify the regex for "quit" or whatever. Here the loop exits on a blank line - is that what you wanted?
    #!/usr/bin/perl -w use strict; my $cmd; while ((print "enter cmd: "), $cmd=<STDIN> and $cmd !~/^\s*$/) { chomp $cmd; print "cmd was: $cmd\n"; } print "loop exited\n";
    Update: Perhaps you wanted to loop until the first non-blank line was entered?
    my $cmd=""; until ($cmd !~ /^\s*$/){print "enter cmd: "; $cmd=<STDIN>;} chomp $cmd; print "cmd was: $cmd\n";
    I guess I'm not so clear about exactly you want to do.

    Basically, I try to construct these loops such that the "last;" statement if any, is not the main, "normal" way that the loop exits. I use that to mean, "oh, we are quitting abnormally early" for some reason - maybe finding the first match or something like that.

    If you are wondering why I used a regex, normally leading/trailing blanks on user input are ignored and I would have some statement to trim these instead of just a simple chomp; Anyway 3 spaces and one tab should be counted as just a "whitespace" line.

      Thanks you!