Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

My dilemma is this...
I have 2 arrays:
example.
@array1 = (234, 453, 111, 239);
@array2 = (v204_txt, v234_txt, v450_txt, v453_txt,);

What I'd like to do is use each element in turn from @array1 as a pattern match for elements in @array2 and push matching element from @array2 into a 3rd array. Currently I'm doing pattern matching gymnastics to parse @array2 down to just the 3 digits into a different array and running an exact compare using a hash. I'm thinking there's a better, cleaner way but my Perl Fu is not very advanced.... Without using modules btw.. Thanks.
  • Comment on Array compare using elements as the pattern match.

Replies are listed 'Best First'.
Re: Array compare using elements as the pattern match.
by toolic (Bishop) on Dec 12, 2014 at 21:08 UTC
    use warnings; use strict; use Data::Dumper; my @array1 = qw(234 453 111 239); my @array2 = qw(v204_txt v234_txt v450_txt v453_txt); my @a3; for (@array2) { for my $pat (@array1) { if (/$pat/) { push @a3, $_; last; } } } print Dumper(\@a3); __END__ $VAR1 = [ 'v234_txt', 'v453_txt' ];
      ++, just a small note: if @array1 contains strings to be matched exactly instead of regular expressions, the pattern should be written /\Q$pat\E/ (quotemeta)

        Alternately:

        for (@array2) { for my $pat (@array1) { if (index($_,$pat) > -1) { push @a3, $_; last; } } }

        For exact matches, index will be faster.

        A more Perl-ish way:

        for my $pat (@array1) { push @a3, grep { index($_,$pat) > -1 } @array2; }
      Nice and simple...
      I should've been able to come up with that....arrrrggg my brain hurts today.
      Thank you so much.
Re: Array compare using elements as the pattern match.
by BillKSmith (Monsignor) on Dec 13, 2014 at 14:27 UTC
    Here is a slightly shorter version:
    use strict; use warnings; use Data::Dumper; my @array1 = qw(234 453 111 239); my @array2 = qw(v204_txt v234_txt v450_txt v453_txt); my @array3 = grep {my $val=$_; grep {$val=~/$_/} @array1} @array2; print Dumper(\@array3);
    Bill
Re: Array compare using elements as the pattern match.
by choroba (Cardinal) on Dec 14, 2014 at 21:52 UTC
    You can build a pattern from array 1 and find all matches in array 2:
    #!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @array1 = qw(234 453 111 239); my @array2 = qw(v204_txt v234_txt v450_txt v453_txt); my $pat = join '|', map quotemeta, @array1; my @array3 = grep /$pat/, @array2; print Dumper(\@array3); __END__ $VAR1 = [ 'v234_txt', 'v453_txt' ];
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ