Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: grep2 (like 'grep', but also return non-matches)

by BrentDax (Hermit)
on Jan 24, 2005 at 19:32 UTC ( [id://424680]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://424680]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-05-18 07:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found