CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
List::MoreUtils - any

 



sriharsha_12
Novice

Aug 30, 2016, 11:36 PM

Post #1 of 3 (2360 views)
List::MoreUtils - any Can't Post

Hi,

When there is a match I'm trying to print both $val & $_ but $1 returns no value. How to get this value?


Code
my @a = ('sample', 'value'); 
my @b = ('amp', 'test');

foreach my $val (@a)
{
if (any {$val =~ /($_)/} @b)
{
say "'$val' '$1'";
}
}

Current o/p:
'sample' ''

Expected o/p:
'sample' 'amp'


BillKSmith
Veteran

Aug 31, 2016, 5:26 AM

Post #2 of 3 (2352 views)
Re: [sriharsha_12] List::MoreUtils - any [In reply to] Can't Post

At best, it is poor practice to use $1 anywhere other than immediately after the regex that sets it. Unexpected results are common.

The solution to your problem is to use a more appropriate utility.

Code
use strict; 
use warnings;
use v5.10;
use List::MoreUtils qw(first_value);
my @a = ('sample', 'value');
my @b = ('amp', 'test');

foreach my $val (@a)
{
if (my $match = first_value {$val =~ /($_)/} @b)
{
say "'$val' '$match'";
}
}


OUTPUT:
'sample' 'amp'

Good Luck,
Bill


sriharsha_12
Novice

Aug 31, 2016, 8:50 PM

Post #3 of 3 (2338 views)
Re: [BillKSmith] List::MoreUtils - any [In reply to] Can't Post

Thanks Bill for the solution. It works. Also thanks for the tip on $1.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives