如何检测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"; }
}
Run Code Online (Sandbox Code Playgroud)
使用
while (defined($input = <STDIN>)) {
...
}
Run Code Online (Sandbox Code Playgroud)
当用户进入Ctrl-D时,<STDIN>将返回undef.
更一般地说,你可以做到
while (defined($input = <>)) {
...
}
Run Code Online (Sandbox Code Playgroud)
并且您的程序将从任何命名的文件中读取输入@ARGV,或者从<STDIN>没有命令行参数的读取输入.