【问题标题】:Printing arrays to .txt file将数组打印到 .txt 文件
【发布时间】:2013-11-04 19:20:04
【问题描述】:

我正在尝试将数组中的前 250 个条目打印到 .txt 文件中,但遇到了一些问题。当我按原样运行脚本时,我的 output.txt 文件中什么也没有。

    #! /usr/bin/perl
use strict;
use warnings;

my $line;
my @array;
my $file = "moloch_chunker_output.txt";

open (OUT , ">","moloch_chunker_output.txt")or die "cant open: $!";
while ($line  = <>){
        chomp($line);
        push(@array, $line);
        if(@array == 250){
                print OUT @array;
}
}

我知道我在这里遗漏了很多东西,但是我在 if 语句之后尝试了其他几种方法。

if(array == 250){
         print "[", join(",",@array),"]","\n";

完全按照我的意愿工作。我只想将它写入 .txt 文件,而不是简单地打印到屏幕上。如何将数组打印到 .txt 文件?

【问题讨论】:

  • 您的脚本有效,但一切都在一行中。可能你不需要chomp 电话。
  • 您的脚本可以替换为perl -pe 'exit if $. &gt; 250' &gt; moloch.txt
  • 是的,你是对的。我不得不不好意思地承认我检查的是 moloch_chunker_out.txt 而不是 moloch_chunker_output.txt。话虽如此,使用 print OUT @array;打印所有内容,但没有我需要的格式;数组实体以逗号分隔,数组末尾带有“[”“]”。
  • @Tim Peoples 使用 head 是一个绝妙的主意,并且可以完美地工作,但是 由数千行实体组成,所有这些都需要被分块成一行250 个。我的下一步是刷新数组并继续从 的第 251 个条目构建

标签: arrays perl printing


【解决方案1】:

与其将所有内容填充到一个数组中,然后在其大小达到 250 时打印数组内容,也许您可​​以简单地启动一个计数器并打印您看到的每一行(然后在达到 250 时退出)。有点像:

$cnt = 0;
while (<>) {
    chomp;
    print;
    last if ++$cnt >= 250;
}

或者...您可以从命令行运行 head -250 moloch_chunker_output.txt(完全跳过 Perl)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2021-03-19
    • 2016-08-02
    相关资源
    最近更新 更多