in reply to Re^2: Unix 'grep -v' equivalency in Perl (was: Perl Regex Question)
in thread Unix 'grep -v' equivalency in Perl (was: Perl Regex Question)

I don't think the purported similarity to goto is a good reason to not use Perl's loop control facilities. OK, the construct is abusable (what construct is not?), but when used appropriately I think that it clarifies things immensely.

FWIW the following article on Loop Exits and Structured Programming helped shaped my thinking on this.

  • Comment on Re (tilly) 3: Unix 'grep -v' equivalency in Perl (was: Perl Regex Question)

Replies are listed 'Best First'.
Re: Re (tilly) 3: Unix 'grep -v' equivalency in Perl (was: Perl Regex Question)
by runrig (Abbot) on Jul 10, 2001 at 02:07 UTC
    I agree. Consider the alternative (warning: marginally yucky code ahead):
    while (<INPUT>) { my $skip; for my $match (@list) { $skip = 1, last if /$match/; } next if $skip; print; }
      Of course, you could always use grep in your grep equivalent:
      foreach my $line (<INPUT>) { next if (grep{$line =~ /\Q$_\E/}@list); print $line; }
        In this case you can live without any loop control at all:
        while (defined(my $line = <INPUT>)) { print $line if not grep {line =~ /\Q$_\E/} @list; }
        However if you have reason to believe that one or two of the matches is likely to knock out most of the input, using loop control explcitly will be more efficient. (So will using qr// to turn the list into REs up front and stop compiling them on each line.) So even though this algorithm can be cleanly expressed with loop control it may be worthwhile to use it anyways.

        Another incidental note. When processing the input of files, I use while rather than foreach whenever reasonable. The reason is that foreach puts the input into list context, which slurps the file. This can potentially take a large amount of memory. By contrast while processes the file incrementally. If you ever have occasion to work with large files, the distinction will matter.