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

后端 未结 3 1889
忘了有多久
忘了有多久 2021-01-22 17:42

My perl script takes any number of files, opens them, and reads one line from each. But it\'s not working. Here\'s my code.

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


        
相关标签:
3条回答
  • 2021-01-22 18:36

    Your <> is being interpreted as a file glob instead of a readline.

    Use the following to explicitly specify your intent:

    $line[$i] = readline $fh[$i];
    
    0 讨论(0)
  • 2021-01-22 18:38

    [Not an answer, but a comment that doesn't fit as a comment]

    Always use 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]"; 
    }
    
    0 讨论(0)
  • 2021-01-22 18:44

    Use readline instead of <>.

    perlop says:

    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

    0 讨论(0)
提交回复
热议问题