Get the intersection of two string lists in Perl

In Chapter 4, Section 4.8 (Computing Union, Intersection, or Difference Unique Lists), the Perl Cookbook provides this technique for getting the intersection of two lists of integers:

@a = (1, 3, 5, 6, 7, 8); @b = (2, 3, 5, 7, 9); ... foreach $e (@a, @b) { $union{$e}++ && $isect{$e}++ } @union = keys %union; @isect = keys %isect; 

I want this to be done (case insensitive) for two line lists. Any effective method please?

+6
source share
3 answers

Array :: Utils is what you are looking for.

 use Array::Utils qw(:all); my @a = qw( abcd ); my @b = qw( cdef ); my @isect = intersect(@a, @b); print join(",",@isect) . "\n"; 

This gives the expected result.

 c,d 

Edit: I did not notice that you wanted to do this unnoticed. In this case, you can replace @a with map{lc}@a (as well as @b ).

+14
source

Here is one map / grep approach:

 my @a = qw(Perl PHP Ruby Python C JavaScript); my @b = qw(erlang java perl python c snobol lisp); my @intersection = grep { defined } @{ { map { lc ,=> $_ } @a } } { map { lc } @b }; # @intersection = qw(Perl Python C) 
+3
source

The least amount of change is required from the original solution. Just lowercase strings.

 @a = qw( abcd ); @b = qw( CDEF ); ... foreach $e (@a, @b) { $union{lc $e}++ && $isect{lc $e}++ } @union = keys %union; @isect = keys %isect; 
+2
source

Source: https://habr.com/ru/post/899735/


All Articles