in reply to grep2 (like 'grep', but also return non-matches)

You might be interested in my List::Part module, which basically does the same thing in a more general way.

use List::Part; ($letters, $numbers)=part { /\d/ } qw(a b c 1 2 3);

The main function of the module looks like this:

sub part(&@) { my $code=shift; my @ret; for(@_) { my $i=$code->($_); next unless defined $i; push @{$ret[$i]}, $_; } return @ret; }

=cut
--Brent Dax
There is no sig.

Replies are listed 'Best First'.
Re^2: grep2 (like 'grep', but also return non-matches)
by Tanktalus (Canon) on Jan 24, 2005 at 19:39 UTC

    Could I please ask that anyone who plays with $_ like this ... please localise it?

    sub part(&@) { my $code=shift; my @ret; local $_; for(@_) { my $i=$code->($_); next unless defined $i; push @{$ret[$i]}, $_; } return @ret; }

    Thanks. There are some really hard-to-figure-out bugs that creep up on people when the subs they call go and affect $_ like this.

    Tanktalus, twice bitten, once shy. Or something like that.

      perlsyn sez about foreach:

      ...the variable is implicitly local to the loop and regains its former value upon exiting the loop.

      So I think this is quite safe.

      =cut
      --Brent Dax
      There is no sig.