简体   繁体   English

Perl如何从作为数组元素的文件句柄中读取一行

[英]Perl how to read a line from a file handle that is an array element

My perl script takes any number of files, opens them, and reads one line from each. 我的perl脚本接收任意数量的文件,打开它们,然后从每个文件中读取一行。 But it's not working. 但这不起作用。 Here's my code. 这是我的代码。

#!/bin/perl
$numfile = scalar @ARGV;

for ($i = 0; $i < $numfile; ++$i)
{
    open $fh[$i],"<",$ARGV[$i];
    $line[$i] = <$fh[$i]>;
}

for ($i = 0; $i < $numfile; ++$i) 
{ 
    print  "$i => $line[$i]"; 
}

Any ideas why this doesn't work? 任何想法为什么这不起作用? Is it illegal to store file handles in an array? 将文件句柄存储在数组中是否合法?

I expect this to print the first line of each file. 我希望这能打印每个文件的第一行。 Instead I get 相反,我得到

0 => GLOB(0x36d190)1 =>

I am using perl v5.18.2 我正在使用Perl v5.18.2

Use readline instead of <> . 使用readline代替<>

perlop says: perlop说:

If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed 如果尖括号中的内容既不是文件句柄,也不是包含文件句柄名称,typeglob或typeglob引用的简单标量变量,则将其解释为将被文件化的文件名模式

Your <> is being interpreted as a file glob instead of a readline . 您的<>被解释为一个文件glob代替readline

Use the following to explicitly specify your intent: 使用以下内容明确指定您的意图:

$line[$i] = readline $fh[$i];

[Not an answer, but a comment that doesn't fit as a comment] [不是答案,而是不适合作为评论的评论]

Always use use strict; use warnings; 始终使用use strict; use warnings; use strict; use warnings; . You are severely handicapping yourself without them. 如果没有他们,您将严重妨碍自己。

You don't need to use multiple handles since you never need more than one at a time. 您不需要使用多个句柄,因为您一次不需要多个。

Some other cleanups: 其他一些清理:

#!/bin/perl

use strict;
use warnings;

my @first_lines;

for my $qfn (@ARGV)
{
    open(my $fh, '<', $qfn)
        or die("Can't open $qfn: $!\n");

    push @first_lines, scalar( <$fh> );
}

for my $i (0..$#first_lines)
{ 
    print  "$i => $first_lines[$i]"; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM