Perl: find if variable value matches in array

I am new to perl. I have code in which a variable is loaded with multiple values โ€‹โ€‹during a foreach loop. What I want to do is to perform some operation on this variable only if it is in this array. What is the most efficient way to do this in perl, since the data that I work is very large.

A simple example of my question: let's say I have a set of fruits that I want

@fruits_i_like = qw (mango banana apple); 

But I have a $ fruit variable in the foreach loop that gets the name of the fruit from a data file that has all the different types of fruits. How can I select only those cases of $ fruit that are in my @fruits_i_like array?

+7
arrays regex perl
source share
3 answers

You can use the hash as follows:

 my %h = map {$_ => 1 } @fruits_i_like; if (exists $h{$this_fruit}) { # do stuff } 

Here is a benchmark comparing this method with vs mfontani solution

 #!/usr/bin/perl use warnings; use strict; use Benchmark qw(:all); my @fruits_i_like = qw/mango banana apple/; my $this_fruit = 'banana'; my %h = map {$_ => 1 } @fruits_i_like; my $count = -3; my $r = cmpthese($count, { 'grep' => sub { if ( scalar grep $this_fruit eq $_, @fruits_i_like ) { # do stuff } }, 'hash' => sub { if (exists $h{$this_fruit}) { # do stuff } }, }); 

Output:

  Rate grep hash grep 1074911/s -- -76% hash 4392945/s 309% -- 
+10
source share

Perl 5.10 or higher?

 use strict; use warnings; use 5.10.0; my @fruits_i_like = qw/mango banana apple/; my $this_fruit = 'banana'; if ( $this_fruit ~~ \@fruits_i_like ) { say "yummy, I like $this_fruit!"; } 

Until 5.10:

 use strict; use warnings; my @fruits_i_like = qw/mango banana apple/; my $this_fruit = 'banana'; if ( scalar grep $this_fruit eq $_, @fruits_i_like ) { print "yummy, I like $this_fruit!\n"; } 

The downside is that the entire array is parsed to find matches. This may not be the best option, in which case you can use List::MoreUtils ' any() , which returns true when it matches the value and does not continue to pass through the array.

 use strict; use warnings; use List::MoreUtils qw/any/; my @fruits_i_like = qw/mango banana apple/; my $this_fruit = 'banana'; if ( any { $this_fruit eq $_ } @fruits_i_like ) { print "yummy, I like $this_fruit!\n"; } 

Happy hack!

+11
source share

This is a search issue. It would be faster to look for @fruits_i_like values โ€‹โ€‹in a hash, for example, %fruits_i_like (which is O (1) and O (n) of the array).

Convert the array to a hash using the following operation:

 open my $data, '<', 'someBigDataFile.dat' or die "Unable to open file: $!"; my %wantedFruits; @wantedFruits{@fruits_i_like} = (); # All fruits_i_like entries are now keys while (my $fruit = <$data>) { # Iterates over data file line-by-line next unless exists $wantedFruits{$fruit}; # Go to next entry unless wanted # ... code will reach this point only if you have your wanted fruit } 
+9
source share

All Articles