Search code examples
regexperlgrep

How can I select certain elements from a Perl array?


I want to search for all elements in an array which have the same starting set of characters as an element in another array. To make it clear:

@array = ("1a","9","3c");
@temp =("1","2","3");

I want to print only 1a and 3c. When I try to use the following program it prints out all the elements in the array instead of the two I want:

foreach $word (@temp)
{
    if( grep /^$word/ , @array) 
    {
        print $_;
    }
}

Solution

  • This answer will do what the OP wants as well as prevent any duplicates from printing on the screen through the use of a hash lookup.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my @array = ("1a","9","3c","3c");
    my @temp =("1","2","3");
    
    my %dups_hash;
    
    for my $w (@temp) {
        my ($match) = grep /^$w/, @array;
    
        # Need to check if $match is defined before doing the hash lookup.
        # This suppresses error messages for uninitialized values; if defined($match) is
        #  false, we short circuit and continue in the loop.
        if(defined($match) && !defined($dups_hash{$match})) {
            print $match;
        }
    }