我的代码不会在" exit;" 之前运行最后一行,我不知道为什么.我之前试图增加printf $fh一条线exit,但这也没有用; 它不会打印任何一行.除了退出前的最后一个打印语句外,其他所有内容都打印正常.
任何线索为什么会这样?或者更好的是,如何修复或解决它?
if($i>0 && $i<3)
{
printf $fh "Partial match found.\n";
if($matched_uid){printf $fh "UID #: ".$arguid." exists.\n";}
if($matched_id){printf $fh "ID #: ".$argid." exists.\n";}
if($matched_uname){printf $fh "Username: ".$arguname." exists.\n";}
printf $fh "Aborting.";
exit;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我复制的部分代码包含此内容
select $fh; $| = 1; #set auto flush
Run Code Online (Sandbox Code Playgroud)
也许这就是我的结果无法复制的原因....
Ken*_*ric 10
我给了R. Bemrose我的投票,但是如果$ fh是一个FILE HANDLE,你可能还想close在终止之前.
另外,你printf错误地使用了.printf 不是 '打印文件'.它的'打印格式'.
对于最后一个例子
print $fh 'Message' ;
Run Code Online (Sandbox Code Playgroud)
是你所需要的全部.
printf 因此可以使用:
printf $fh 'some format %s and more %s ' , $var , $var ;
Run Code Online (Sandbox Code Playgroud)
要么
printf 'some format %s and more %s ' , $var , $var ;
Run Code Online (Sandbox Code Playgroud)
和它的平等
print $fh sprintf 'format %s more %s' , $var , $var ;
Run Code Online (Sandbox Code Playgroud)
因此,如果您的任何连接变量扩展到其中包含'%',那么您就会冒不必要的代码风险.有关落入此陷阱的人员的示例,请参阅问:308417:为什么我的Perl脚本会从文件中删除字符?
perldoc -f printprint FILEHANDLE LIST print LIST print Prints a string or a list of strings.
perldoc -f printf
printf FILEHANDLE FORMAT, LIST
printf FORMAT, LIST
Equivalent to "print FILEHANDLE sprintf(FORMAT, LIST)", except that "$\"
(the output record separator) is not appended
我一直在探讨你的问题,因为我无法让你的"缓冲"状态发生.无论我是否冲洗它们,我的所有文件都会被正确刷新.(Perl 5.10).
继承我正在尝试的代码片段:
#!/usr/bin/perl
use strict;
use warnings;
open my $fh , '>' , '/tmp/oo.txt';
my $exit_at = int(rand( 200_000 ));
print "$exit_at\n";
sleep 2;
for ( 0 .. ( $exit_at * 2 ) ){
print $fh $_;
if ( $_ == $exit_at ){
printf $fh '%n' ; # Bad Code Causes Early Death.
printf $fh 'last line';
exit;
}
if ( $_ % 1000 ){
print $fh "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用你错过的printf.被注释的行会弹出一条错误消息,因为它没有提供'n'参数而无效,并且它会因:
Modification of a read-only value attempted at iotest.pl line 15.
Run Code Online (Sandbox Code Playgroud)
在执行"最后一行"打印之前(也很糟糕,但是没有%符号,所以它很好)使输出文件中不存在"最后一行".
请修改你的printf并使用普通旧打印,看看是否能解决你的问题.
Perl缓冲其输出.你可以用关闭自动缓冲
local $| = 1;
Run Code Online (Sandbox Code Playgroud)
编辑:我莫名其妙地打!而不是| 第一次......固定.不知道是怎么回事,他们在键盘的两侧.