【问题标题】:Input a list from a file in Perl在 Perl 中从文件中输入列表
【发布时间】:2014-12-03 14:25:54
【问题描述】:

我想从 Perl 的列表中输入数据。到目前为止,我一直在将数据列表粘贴到实际程序中以供其处理。我原来的排序程序是这样的:

# /perl/bin


use strict; #force perl to code properly
use warnings; #find typing mistakes in program like missing semicolons, etc.

use Text::ParseWords; #parse text into an array of tokens or array of arrays

my @rows;

while (<DATA>) {
    push @rows, [ parse_line(',', 0, $_) ];
}

@rows = sort { $a->[2] <=> $b->[2] } @rows;

open OUTPUT, ">OUTPUT.TXT";

foreach (@rows) {
    print OUTPUT join ',', @$_;
}

__DATA__
SMITH,M,1
JONES,F,1
...

但我希望它从具有此列表的文件中输入。我不确定我是否走在正确的轨道上,但这就是我目前所拥有的:

# /perl/bin


use strict;                     #force perl to code properly
use warnings;                   #find typing mistakes in program like missing semicolons, etc.
use autodie;                    #replace functions with ones that succeed or die with lexical scope

use Text::ParseWords;               #parse text into an array of tokens or array of arrays

open(MYINPUTFILE, "<inputfile.txt");        # open for input

my @rows = <MYINPUTFILE>;               # read file into list

while (<MYINPUTFILE>) {
    push @rows, [ parse_line(',', 0, $_) ];
}

@rows = sort { $a->[2] <=> $b->[2] } @rows;

open OUTPUT, ">OUTPUT.TXT";

foreach (@rows) {
    print OUTPUT join ',', @$_;
}

【问题讨论】:

  • 您向我们展示了一点XY problem。你到底想用你的代码做什么?根据第三个字段对 CSV 中的行进行排序?
  • 是的,这正是我想要做的。很抱歉出现 XY 问题,我什至不知道我在做什么!
  • 有什么问题?任何输出?

标签: perl list file text input


【解决方案1】:

这是你问题的症结所在:

open(MYINPUTFILE, "<inputfile.txt");        # open for input

my @rows = <MYINPUTFILE>;               # read file into list

因为 "@rows =" 给出了一个 "wantarray" 或列表 右侧的上下文, "" 读取整个文件。

然后:

while (<MYINPUTFILE>) {                 # try to read file again,
                                        # but you've already read it all
    push @rows, [ parse_line(',', 0, $_) ];
}

您正在尝试读取文件两次。

您的代码还有其他问题,但您可能只想写:

open(MYINPUTFILE, "<inputfile.txt");        # open for input

my @rows;

while (<MYINPUTFILE>) {
    push @rows, [ parse_line(',', 0, $_) ];
}

...与您的早期版本并行。

至少,您可能会考虑对 Perlish 进行一些更改;

打开我的 $input_file, '

在比这个更复杂的情况下,使用词法(“my”)变量而不是 *FILEHANDLE 更好。 (除此之外,您可以更轻松地将其传递给子例程。)如果您允许其他人为您的程序指定文件名,使用open 的三参数形式也可以防止出现问题。然后,您将在 while 循环中使用 &lt;$input_file&gt;。

【讨论】:

  • 但是,应该是open(...) or die 或use autodie;。
  • @Axeman OP 使用 autodie 在他们的“这就是我目前所拥有的”脚本中。
  • @ialarmedalien。错过了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 2013-10-18
  • 2020-09-16
相关资源
最近更新 更多