Gossamer Forum
Quote Reply
grep
Is there a way to grep using a list rather than a regex?

For example I can do:

Code:
my %OK = map { $_ => $self->{cgi}->param($_) } grep ( /^foo|bar$/, $self->{cgi}->param());

...but I want to do something like:

Code:
my @list = qw/foo bar/;
my %OK = map { $_ => $self->{cgi}->param($_) } grep ( @list , $self->{cgi}->param());

Is there a way to do something like that?

Last edited by:

Paul: Jul 12, 2002, 11:04 AM
Quote Reply
Re: [Paul] grep In reply to
In Reply To:

Code:
my @list = qw/foo bar/;
my %OK = map { $_ => $self->{cgi}->param($_) } grep ( @list , $self->{cgi}->param());

Is there a way to do something like that?

I'd say the easiest way of doing something like that is:

Code:

my %list = map {($_=>1)} qw/ foo bar /;
my %OK = map { $_ => $self->{cgi}->param($_) } grep { $list{$_} } $self->{cgi}->param();

However, another way of going about it may be:

Code:

my ( %OK, $res );
foreach my $wanted ( qw( foo bar ) ) {
next unless ( defined $res = $self->{cgi}->param($wanted) );
$OK{$wanted} = $res;
}

You can probably scrunch that into one line of code at the sacrifice of readability Wink

Last edited by:

Aki: Jul 12, 2002, 11:24 AM
Quote Reply
Re: [Aki] grep In reply to
Ah cool, the first example did what I wanted, (after removing the comma in the grep Cool)

Thanks.
Quote Reply
Re: [Paul] grep In reply to
whoops fixed. Blush