【问题标题】:foreach condition working wrong in perl?foreach 条件在 perl 中工作错误?
【发布时间】:2023-03-05 19:22:01
【问题描述】:

下面是我的 perl 脚本

@array = qw(one two three four five);
sleep (60);
foreach (@array){
    open(new,">>$_.txt");
    print new "$_ This is testing\n";
}
sleep(120);
open (new2,">>for2.txt");
print new2 "Hai";

在我的脚本中。新文件由 foreach 条件打开。在我的脚本中打开五个文件。 但我的问题是首先打开新的五个文件,但没有写入打开文件的最后一个数组元素。完成条件的外部后,仅写入 foreach 最后一个元素文件。例如:创建新文件 一二三四五,并将 $_ this is testing 写入当文件 for2 创建并将值写入文件然后文件 是涉及写作。怎么改啊。?

【问题讨论】:

  • 是的,foreach 在 Perl 中被破坏了……你是第一个注意到它的人。 ...另外,使用词法文件句柄,例如open my $new

标签: perl


【解决方案1】:

文件句柄的输出是缓冲的,通常只有当缓冲区已满或文件句柄关闭时才会刷新。如果您在同一个句柄上打开另一个文件,或者当程序终止时,Perl 会隐式关闭文件句柄。

解决方案是将文件句柄设置为 autoflush,如下所示。如果您在 Perl 5 版本 14 之前的旧版本 Perl 上运行,那么您还需要在程序顶部添加 use IO::Handle;

foreach (@array){
    open(new,">>$_.txt");
    new->autoflush;
    print new "$_ This is testing\n";
}

更新

您应该注意一些事项,这将极大地改进您的 Perl 编程

  • 您必须始终将use strictuse warnings 放在您编写的每个 Perl 程序的顶部,并尽可能晚地使用my 声明所有变量

  • 你应该使用open的三参数形式和词法文件句柄,并且你必须始终检查open调用是否成功,否则后续的读取和写入将失败,继续没有意义

  • 您应该使用大量的空白来更好地布局您的代码并使其更具可读性

我会像这样在你的问题中编写代码

use strict;
use warnings;

my @files = qw( one two three four five );

sleep(60);

for my $name ( @files ){
   my $file = "$name.txt";
   open my ($new_fh), '>>', $file or die "Unable to open '$file' for appending: $!";
   $new_fh->autoflush;
   print $new_fh "$name This is testing\n";
}

sleep(120);

open my ($fh_new2), '>>', 'for2.txt' or die "Unable to open 'for2.txt' for appending: $!";
print $fh_new2 'Hai';

【讨论】:

  • 文件在关闭时会被清除,因此当您切换到文件句柄的词法变量时,$new_fh->autoflush; 变得毫无意义。
【解决方案2】:

当您打开同名的后续文件句柄时,您对文件 onefour 的文件句柄将关闭并刷新。但是,最后一个文件的句柄将保持打开状态,直到脚本结束。

解决此问题的一种方法是明确close 您的文件句柄,以便刷新它们。

foreach (@array){
    open(new,">>$_.txt");
    print new "$_ This is testing\n";
    close new;
}

更好的解决方案是使用更多Modern Perl techniques。如果你使用词法文件句柄,它们会在超出范围时自动关闭。

use strict;
use warnings;
use autodie;

my @array = qw(one two three four five);

sleep(60);

for (@array) {
    open my $fh, '>>', "$_.txt";
    print $fh "$_ This is testing\n";
}

sleep(120);

open my $fh, '>>', "for2.txt";
print $fh "Hai";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多