【问题标题】:Perl push function gives index values instead of array elementsPerl push 函数给出索引值而不是数组元素
【发布时间】:2013-08-05 00:45:44
【问题描述】:

我正在读取一个名为mention-freq 的文本文件,其中包含以下格式的数据:

1

1

13

2

我想读取这些行并将值存储在一个数组中,如下所示:@a=(1, 1, 13, 2)。 Perl push 函数给出了索引值/行号,即 1,2,3,4,而不是我想要的输出。你能指出错误吗?这是我所做的:

use strict;
use warnings;

open(FH, "<mention-freq") || die "$!";
my @a;
my $line;
while ($line = <FH>)
{
    $line =~ s/\n//;
    push @a, $line;
    print @a."\n";
}
close FH;

【问题讨论】:

  • 我喜欢twoHandsTwoCutsFunction函数:) sub{map{s/^\s+//; s/\s+$//; $_}@_}

标签: arrays perl


【解决方案1】:

错误是您正在打印@a 和换行符的串联。当你连接时,这会强制标量上下文。数组的标量意义不是它的内容,而是它的元素数。

你只是想要

 print "@a\n";

改为。

此外,虽然它不会影响您的代码,但删除&lt;&gt; readline 运算符读入的记录终止符的正常方法是使用chomp

chomp $line;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2018-03-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    相关资源
    最近更新 更多