Sujju
Sujju

Reputation: 97

How to change the value of $_ to what is required inside grep in perl?

In this code, I want to access the value of the key {IS-VAR}, of each element of the array of hashes @Cleared. When it enters inside the loop $_ is set to the value of $_->{'NAME'}.

if (grep {$_->{'NAME'} eq $entity_name} @Cleared)
{
  **$is_var = $_->{'IS-VAR'};**
  $var_flag = 1 if ($is_var =~ /^TRUE$/i);
}

Is there a way to access the value of $_->{'IS-VAR'} inside the loop, $_ being the element of @Cleared in this context?

The structure of @Cleared is as follows:

@Cleared = [NAME => 'xxx',
            TYPE => 'yyy',
            IS-VAR => 'TRUE'];

Upvotes: 3

Views: 243

Answers (2)

erickb
erickb

Reputation: 6309

you can try a simpler for loop:

for my $cleared (@Cleared) {
  if ($cleared->{NAME} eq $entity_name && $cleared->{IS_VAR} eq 'TRUE') {
    $var_flag = 1
   }
}

Upvotes: 0

user1919238
user1919238

Reputation:

The problem with your code is that you are using grep in an if statement. This converts the result of grep into a scalar (which will be the number of elements grep found). Thus you don't actually know which elements match.

If you convert it to a for loop, you will be able to access each element that matched; the rest of your code will work verbatim:

foreach (grep {$_->{'NAME'} eq $entity_name} @Cleared)
{
    $is_var = $_->{'IS-VAR'};
    $var_flag = 1 if ($is_var =~ /^TRUE$/i);
}

However, if you simply want to find whether a single row matched, you could compress it all into a single grep:

my $is_var = grep {
    $_->{'NAME'} eq $entity_name && $_->{'IS-VAR'} =~ /^TRUE$/i
} @Cleared;

Now $is_var contains a count of how many elements matched. if ($is_var) {...} will be true if at least one matched.

grep is not the most efficient way to do it if you only need to know whether there is at least one match, however. Ideally, you should stop as soon as you find a single match:

my $is_var;
foreach (@Cleared)
{
    if ($_->{'NAME'} eq $entity_name && $_->{'IS-VAR'} =~ /^TRUE$/i)
    {
        $is_var = 1;
        last;          #break out of the loop
    }
}

Upvotes: 10

Related Questions