Can I skip a whole file with the <> operator?
Asked Answered
H

3

10

The following Perl code has an obvious inefficiency;

while (<>)
{
if ($ARGV =~ /\d+\.\d+\.\d+/) {next;}
... or do something useful
}

The code will step through every line of the file we don't want.

On the size of files this particular script is running on this is unlikely to make a noticeable difference, but for the sake of learning; How can I junk the whole file <> is working and move to the next one?

The purpose of this is because the sever this script runs on stores old versions of apps with the version number in the file name, I'm only interested in the current version.

Hoofbeat answered 14/9, 2009 at 15:3 Comment(0)
S
15

grep ARGV first.

@ARGV = grep { $_ !~ /\d+\.\d+\.\d+/ } @ARGV;

while (<>)
{
  # do something with the other files
}
Stir answered 14/9, 2009 at 15:57 Comment(1)
IC, you just filter @ARGV like you would any other list.Hoofbeat
C
20

Paul Roub's solution is best if you can filter @ARGV before you start reading any files.

If you have to skip a file after you've begun iterating it,

while (<>) {
    if (/# Skip the rest of this file/) {
        close ARGV;
        next;
    }
    print "$ARGV: $_";
}
Cowan answered 14/9, 2009 at 16:15 Comment(1)
I like this. This way you can easily search files in a directory by keyword: perl -E'@ARGV=<"*">; while(<>){if (/searchedWord/){say $ARGV; close ARGV;}}'Shulem
S
15

grep ARGV first.

@ARGV = grep { $_ !~ /\d+\.\d+\.\d+/ } @ARGV;

while (<>)
{
  # do something with the other files
}
Stir answered 14/9, 2009 at 15:57 Comment(1)
IC, you just filter @ARGV like you would any other list.Hoofbeat
H
9

Paul Roub's answer works for more information, see The IO operators section of perlop man page. The pattern of using grep is mentioned as well as a few other things related to <>.

Take note of the mention of ARGV::readonly regarding things like:

perl dangerous.pl 'rm -rfv *|'
Herne answered 14/9, 2009 at 16:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.