I am trying to use List::MoreUtils methods. But, need some clarity on its usage it in some scenarios.
Please let me know, if it can be used with a map. For example:
#!/usr/bin/perl
use strict;
use warnings;
use List::Util;
use List::MoreUtils;
use Data::Dumper;
my @udData1 = qw(WILL SMITH TOMMY LEE JONES);
my @arr = qw(WILL TOMMY);
my %output = map{$_=>List::MoreUtils::firstidx{/$_/} @udData1} @arr;
print Dumper %output;
print List::MoreUtils::firstidx{/TOMMY/} @udData1;
print "\n";
Output:
$VAR1 = 'TOMMY';
$VAR2 = 0;
$VAR3 = 'WILL';
$VAR4 = 0;
2
As observed I am not getting the values correctly when using map, but getting it fine when used in the later command.
I intend to use $_ as an element of @arr. This may be incorrect. So, please suggest me an alternative. Shall i have to use foreach?
The problem is this bit right here:
In this bit of code, you’re expecting
$_to be both the pattern taken from@arrand the string taken from@udData1at the same time. (Remember thatfirstidx{/TOMMY/}meansfirstidx{$_ =~ /TOMMY/}, and likewisefirstidx{/$_/}meansfirstidx{$_ =~ /$_/}.)What actually happens is that
$_is the value from@udData1(since that’s the innermost loop) and you wind up matching that against itself. Because it’s a simple alphabetic string, it always matches itself, and firstidx correctly returns 0.Here’s one solution using a temporary lexical variable: