gpt4 book ai didi

perl - 为什么 Perl 在退出前不打印最后一个文本?

转载 作者:行者123 更新时间:2023-12-03 18:08:17 24 4
gpt4 key购买 nike

我的代码不会在“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;
}

编辑:
我复制的部分代码包含这个
select $fh; $| = 1; #set auto flush

也许这就是为什么我的结果无法复制的原因....

最佳答案

我给了 R. Bemrose我的投票,但如果 $fh 是 文件句柄 您可能还想 close它在终止之前。

另外,您正在使用 printf错。 printf 是 不是 '打印文件'。它的“打印格式”。

对于最后一个例子

  print $fh 'Message' ;  

是你所需要的全部。
printf旨在用于:
printf $fh 'some format %s  and more %s ' ,  $var , $var ; 

或者
   printf 'some format %s  and more %s ' ,  $var , $var ; 

它相当于做
   print $fh sprintf 'format %s more %s' , $var , $var ; 

正因为如此,如果您的任何连接变量扩展为其中包含 '%',您就会带来不必要的代码风险。有关人们落入此陷阱的示例,请参阅 Q:308417:Why does my Perl script remove characters from the file?
perldoc -f print
print FILEHANDLE LISTprint LISTprint   Prints a string or a list of strings.

perldoc -f printf

printf FILEHANDLE FORMAT, LISTprintf FORMAT, LIST      Equivalent to "print FILEHANDLE sprintf(FORMAT, LIST)", except that "$\"       (the output record separator) is not appended

Further Probing

I've been probing into your problem further because I can't get your "buffering" condition to occur. All my files are properly flushed whether or not I flush them. ( Perl 5.10 ).

Heres my code snippet I'm trying:

#!/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";
}
}

我正在使用你对 printf 的误用。
被注释的行会弹出一条错误消息,因为由于没有人提供 'n' 参数,它无效,并且它以:
Modification of a read-only value attempted at iotest.pl line 15.

在执行“最后一行”打印之前(也很糟糕,但其中没有 % 符号,因此它很好)使“最后一行”从输出文件中消失。

请修复您的 printf 并改用普通旧打印,看看是否能解决您的问题。

关于perl - 为什么 Perl 在退出前不打印最后一个文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/636083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com