Grep with Array

Grep returns a list, bracket will return the actual value. The first argument needs to evaluate as true or false to return the match.

if (my ($matched) = grep $_ eq $match, @array) {
    print "found it: $matched\n";

Convert Array into hash

Converting array to hash with array elements as the hash keys amd values are simply 1.

my %hash = map {$_ => 1} @array;
# check if the hash contains $match
if (defined $hash{$match}) {
    print "found it\n";


Right way to use grep

This is smart match will match the exact word.

if (grep /$match/, @array) {
    print "found it\n";


This will return the number of elements in match which is not correct to use with if to match a specific match.

if (grep($match, @array)) 
{ print "found it\n"; }

Multiple Arrays

Using multiple array to match.

if (grep /$match/, @array, @array1, @array2, @array3)
    print "found it\n";


Leave a Reply

Your email address will not be published. Required fields are marked *