Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^2: cull

by radiantmatrix (Parson)
on Apr 10, 2007 at 16:52 UTC ( [id://609207]=note: print w/replies, xml ) Need Help??


in reply to Re: cull
in thread cull

Interesting. Before reading your comment, I came up with the solution below. The only differences are style (e.g. $code->() vs. &$code) that I refrain from building a return array if the context is void or scalar.

I guess TMTOWTDI leads to some random convergence at times. ;-)

use strict; use warnings; use List::MoreUtils qw[firstidx]; sub cull (&\@) { my ($code, $array) = (shift, shift); my @matches; my $count; # let List::MoreUtils (fast!) find the items # splice() returns the items removed.... while ( (my $idx = firstidx { $code->() } @$array) > -1 ) { my $item = splice(@$array,$idx,1); wantarray ? push(@matches, $item) : $count++; } wantarray ? @matches : $count; } my @test = qw[how I wish I could remember pi easily]; my @new = cull { $_ eq 'I' } @test; print join(':',@new), "\n"; print join(':',@test), "\n";
<radiant.matrix>
Ramblings and references
The Code that can be seen is not the true Code
I haven't found a problem yet that can't be solved by a well-placed trebuchet

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-24 00:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found