Code Comments
Programming Forum and web based access to our favorite programming groups.Hi all,
let's we have:
use strict;
use warnings;
my @input = qw{ one two twentythree four };
my @filter = qw { one three five ten twenty };
my @filtered = ();
for my $in (@input) {
for my $filter (@filter) {
push @filtered, $in if $in =~ /$filter$/i;
}
}
I'd like to get new @filtered array, where will be only values
from @input against @filter.
but my snippet is 6 lines, I think it should be written in 1 line, with
using grep and map, but I'm not sure how.
Also we can say, input is always smaller than @filter (for
optimalization)
Anyone ? :)
Post Follow-up to this message>>>>> "Ing" == Ing Branislav Gerzo <konfera@2ge.us> writes:
Ing> Hi all,
Ing> let's we have:
Ing> use strict;
Ing> use warnings;
Ing> my @input = qw{ one two twentythree four };
Ing> my @filter = qw { one three five ten twenty };
Ing> my @filtered = ();
Ing> for my $in (@input) {
Ing> for my $filter (@filter) {
Ing> push @filtered, $in if $in =~ /$filter$/i;
Ing> }
Ing> }
Ing> I'd like to get new @filtered array, where will be only values
Ing> from @input against @filter.
Ing> but my snippet is 6 lines, I think it should be written in 1 line, with
Ing> using grep and map, but I'm not sure how.
## first, precompile all the regex for speed:
@filter = map qr/$_$/i, @filter;
## now grep the wanteds
my @filtered = grep {
my $wanted = 0;
my $input = $_;
$wanted ||= $input =~ /$_/ for @filter;
$wanted;
} @input;
Note the use of ||= for short-circuiting the tests once a good filter
is found. You can't use "return 1", because a grep/map block is not a
subroutine.
--
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training
!
Post Follow-up to this messageRandal L. Schwartz [RLS], on , , 2005 at 05:47 (-0700) wrote about : RLS> $wanted ||= $input =~ /$_/ for @filter; RLS> $wanted; RLS> } @input; RLS> Note the use of ||= for short-circuiting the tests once a good filter RLS> is found. You can't use "return 1", because a grep/map block is not a RLS> subroutine. very nice example, thanks a lot. -- How do you protect mail on web? I use http://www.2pu.net ["Just give me the original history, please!" -- Sam Beckett]
Post Follow-up to this message
Show a Printable Version
Email This Page to Someone!
Receive updates to this thread
Powered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.