Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl User Input

Tags:

input

perl

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"; }
}
like image 656
lambda Avatar asked Jul 19 '26 01:07

lambda


1 Answers

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.

like image 67
Tim Pierce Avatar answered Jul 21 '26 21:07

Tim Pierce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!