if-map vrs foreach-if

F

fatted

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.
 
P

Perusion hostmaster

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top