Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl Misc (http://www.velocityreviews.com/forums/f67-perl-misc.html)
-   -   if-map vrs foreach-if (http://www.velocityreviews.com/forums/t870148-if-map-vrs-foreach-if.html)

fatted 07-15-2003 01:53 PM

if-map vrs foreach-if
 
I have this piece of code ($db_keywords is an array ref of array
references):

if(map($_->[0] =~ /\b$keyword\b/i,@$db_keywords))
{
print "Matched $keyword\n";
}

Which worked fine and dandy, but I now want to know what the value of
$_->[1] is at a match. Now I achieved this as follows:

foreach my $db_k (@$db_keywords)
{
if($db_k->[0] =~ /\b$keyword\b/i)
{
print "$keyword $db_k->[0] $db_k->[1]\n";
}
}

What I'd like to know though:
Is there a way of achieving this (accessing the 2 values of the array
reference at a matching point in $db_keywords) using the if-map style
syntax I was originally using.

Perusion hostmaster 07-15-2003 02:54 PM

Re: if-map vrs foreach-if
 
On 15 Jul 2003 06:53:34 -0700, fatted <fatted@yahoo.com> wrote:
> I have this piece of code ($db_keywords is an array ref of array
> references):
>
> if(map($_->[0] =~ /\b$keyword\b/i,@$db_keywords))
> {
> print "Matched $keyword\n";
> }
>
> Which worked fine and dandy, but I now want to know what the value of
> $_->[1] is at a match. Now I achieved this as follows:
>
> foreach my $db_k (@$db_keywords)
> {
> if($db_k->[0] =~ /\b$keyword\b/i)
> {
> print "$keyword $db_k->[0] $db_k->[1]\n";
> }
> }
>
> What I'd like to know though:
> Is there a way of achieving this (accessing the 2 values of the array
> reference at a matching point in $db_keywords) using the if-map style
> syntax I was originally using.


Why does it matter? Unless performance is a big issue, I would go
for some simplicity and clarity:

my $regex = qr/\b$keyword\b/;

for my $db_k (@$db_keywords) {
next unless $db_k->[0] =~ $regex;
print "$keyword $db_k->[0] $db_k->[1]\n";
}

Compiling the regex only once is a good idea if you have a sizable
array.

--
Perusion Hostmaster

"Being against torture ought to be sort of a bipartisan thing."
-- Karl Lehenbauer


All times are GMT. The time now is 03:37 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.