How can I detect Ctrl+D in order to break out of the loop in Perl?
while (1){
$input = <STDIN>;
print $input;
#This is where I would check for CTRL+D
#last if ($input equals to CTRL+D); EXIT LOOP
if($input > 0){
print " is positive\n";
}
elsif($input < 0){
print " is negative\n";
}
else { print " is zero\n"; }
}
Use
while (defined($input = <STDIN>)) {
...
}
When the user enters Ctrl-D, <STDIN> will return undef.
More generally, you can do
while (defined($input = <>)) {
...
}
and your program will read input from any files named in @ARGV, or from <STDIN> if there are no command-line arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With