in reply to Empty STDIN does not exit while loop
For terminal user input, I recommend following normal unix conventions: any white space in front does not matter and any white space after the input does not matter. You do not need chomp() when using s/\s*$//; because all line endings are considered white space.
I strongly prefer to put the condition that "ends the loop" in the loop conditional instead of burying it somewhere within the loop's body. With the "comma operator", the only part of the statement that matters for "truthfulness" is the last clause. If there are say 9 things that can end the loop, I would try to put the very most common of those in the conditional and leave the other 8 to be within the loop (e.g. last if XYZ;).
For terminal input like this, consider the following 2 examples:
First, simple Blank Line to exit:
Second, using QUIT, quit or any variation like QuIt to quit:#!/usr/bin/perl use strict; use warnings; my $line; # don't put a my declaration in a loop conditional print "Enter data at prompt, blank line to finish data entry\n"; while ( (print "> "), $line = <STDIN>, $line !~ /^\s*$/) { $line =~ s/^\s*//; # delete leading spaces $line =~ s/\s*$//; # delete trailing spaces # no chomp is needed because both # carriage return and line feed are # white space characters (\s) in Perl # regex lingo print "Data processed:$line\n"; } print "LOOP EXITED DUE TO BLANK LINE\n";
update: changed typo goof in the # comments of \w to \s.#!/usr/bin/perl use strict; use warnings; my $line; # don't put a my declaration in a loop conditional print "Enter data at prompt or type: quit to stop data entry\n"; while ( (print "> "), $line = <STDIN>, $line !~ /^\s*Q(uit)$/i) { $line =~ s/^\s*//; # delete leading spaces $line =~ s/\s*$//; # delete trailing spaces # no chomp is needed because both # carriage return and line feed are # white space characters (\s) in Perl # regex lingo print "Data processed:$line\n"; } print "LOOP EXITED DUE TO QUIT \n";
|
|---|