如何检测Ctrl D以便在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"; } }
解决方法
使用
while (defined($input = <STDIN>)) { ... }
当用户输入Ctrl-D时,< STDIN>将返回undef.
更一般地说,你可以做到
while (defined($input = <>)) { ... }
并且您的程序将读取@ARGV中指定的任何文件的输入,或者来自< STDIN>如果没有命令行参数.