in reply to Reading multiple files one line at a time from arguments

If you didn't care about what file name you're processing, the entire script could look like this:

die "Usage: mytest filename [filename [...]]\n" unless @ARGV; print while <>;

...because (see perlop) the <> operator shifts filenames off of @ARGV and opens them internally. If @ARGV starts out empty, it reads from STDIN instead.

Here's another approach that is quite similar to yours, but borrows the idea of shifting filenames out of @ARGV:

die "Usage: mytest filename [filename [...]]\n" unless @ARGV; while( my $file = shift ) { open my $ifh, '<', $file or die $!; print "$file($.): $_" while <$ifh>; }

Dave

Replies are listed 'Best First'.
Re^2: Reading multiple files one line at a time from arguments
by choroba (Cardinal) on Jun 19, 2014 at 08:06 UTC
    If you didn't care about what file name you're processing
    Even if you did, you could retrieve it from $ARGV, see perlvar.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      ++! I knew I was forgetting something useful.

      In that case:

      die "Usage: mytest filename [filename [...]]\n" unless @ARGV; while ( <> ) { print "$ARGV($.): $_" } continue { close ARGV if eof }

      That will print current file, current line number, and then the line. The continue clause serves to reset the line number before moving on to the next file. Otherwise $. would just keep counting upward, giving a total for all files.

      I have no idea why I indented it that way. Just looking for symmetry or something, I guess.


      Dave

        You can assign to $. directly. It might tell the purpose more clearly.
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ