Reputation: 25113
I looking for field name where search
text is found
my $field;
for $field ( qw' email phone name ' ) {
last if $user->$field =~ /$search/;
}
print $field; # undef
Here if $user->email
matched then the last
command is called.
Thus I expect $field
should have email
as value. But it is actually undef
Why value of $field
variable after the loop is undef
?
Upvotes: 3
Views: 108
Reputation: 510
Your code is not working since the "$field" is in global scope it is implicitly localised in the for loop since the same variable is used there as well. If your requirement is just to print or get the matched value in a variable then your code should be similar to :
#This variable will have the field name
my $result;
foreach my $field ( qw ' email phone name ' ) {
if ($user->{$field} =~ /$search/) {
$result = $field;
last;
}
}
print $result;
or, grep can be used to filter values from an array. Filtering values using Perl grep
P.S. updated my answer after @Eugen's comment.
Upvotes: 1
Reputation: 49
You will get more detail understanding from below example.
1 #!/usr/bin/perl
2
3 my $field;
4 my $user = {
5 'email' => '[email protected]'
6 };
7
8 foreach my $search ( "email" , "phone", "name" ) {
9 if ($user->{$search} ){
10 $field = $user->{$search};
11 last;
12 }
13 }
14 print "\n===field========$field====\n";
Upvotes: 0
Reputation: 385536
The loop var is scoped to the loop.
Use
my ($field) = grep { $user->$_ =~ /\Q$search/ } qw( email phone name );
or
use List::Util qw( first );
my $field = first { $user->$_ =~ /\Q$search/ } qw( email phone name );
Upvotes: 4