How to get elements from one array but not in another array in perl

How to get elements from one array but not in another array.

Or, in other words, how to get elements from one array minus elements from another array.

The task can be simplified and made efficient (less loops and less iterations) by creating a hash (associative array) from one array elements and then matching all the elements of the other array one by one. Example,

#!/usr/bin/perl -w

@content = (1,2,3,4,5,6,7,8,9,'a','b','c','d','e');
@alphabets = ('a','b','c','d','e','f','g','h');

# create a hash with elements of @alphabets as keys and assign them a value 1
%alpha_hash =();
foreach my $alpha (@alphabets)
{
   $alpha_hash{$alpha} = 1;
}

foreach $elem (@content)
{
    unless ($alpha_hash{$elem}) # it's not in %alpha_hash, so this is what we need
    {     
        print $elem."\n";          #it is the one not present in $alphabets 
    }
}

Instead of printing the $elem we can store it in some array, suppose @result, then this array can be visualized to be subtraction of the two.

@result = @content – @alphabets

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>