For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > June 2005 > array against array regexp









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author array against array regexp
Ing. Branislav Gerzo

2005-06-05, 3:56 pm

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 ? :)



Randal L. Schwartz

2005-06-05, 3:56 pm

>>>>> "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!
Ing. Branislav Gerzo

2005-06-06, 8:55 am

Randal 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]


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com