'Perl- Making a "Do While" exit when the input is an integer number or empty
I have this "Do While" loop and I want to exit it when the user's input is an integer number or empty but I am having some troubles implementing this behavior.
do {
$input = <STDIN>;
} while ($input != "" && $input !~ /^\d+$/ );
Is there any way to interrupt the loop manually like for example
if($input == " "){
break;
}
Solution 1:[1]
The keyword for breaking out of a loop in Perl is last, but that doesn't work for the do { ... } while construct because do is not a loop block.
Your code is almost correct. You need to chomp your $input to remove trailing newlines, and it will work.
Solution 2:[2]
The underlying problem is that the input isn't an empty string when someone presses just enter; it's a line feed. Using chomp will remove that line feed.
my $input;
do {
chomp( $input = <> );
} while $input ne "" && $input !~ /^\d+\z/;
Note the use of ne to compare strings. Always use use strict; use warnings;!
One could also use
my $input;
do {
chomp( $input = <> );
} while $input !~ /^\d*\z/;
But let's answer the explicitly-asked question.
Perl has the (IMHO better-named) last operator. (See also: next, redo)
Unfortunately, do BLOCK while EXPR is a special case of the EXPR while EXPR; statement modifier, and last doesn't affect loops created by statement modifiers.
To use last, the loop could be reworked into an infinite loop.
my $input;
while (1) {
chomp( $input = <> );
last if $input =~ /^\d*\z/;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ikegami |
