in reply to intersection of N arrays

This one takes care of that pesky "more than one instance of X in array Y" test case:
use strict; our %ids; sub intersect { my %count; my @ret; my $count = scalar keys %ids; foreach my $key (keys %ids) { my %this; for (@{$ids{$key}}) { next if $this{$_}; $count{$_}++; $this{$_}++; if ($count{$_} == $count) { push @ret, $_; } } } undef %ids; return @ret; } $ids{'foo'} = [ 3, 4, 4, 5 ]; $ids{'bar'} = [ 3 ]; $ids{'zoo'} = [ 3, 4, 5 ]; print "[ ",join(', ',intersect)," ]\n"; # prints "[ 3 ]"

Replies are listed 'Best First'.
Re^2: intersection of N arrays
by Solo (Deacon) on Jul 01, 2004 at 13:29 UTC
    The line
    next if $this{$_};
    should test existence rather than truth, like so
    next if exists $this{$_};
    --Solo
    --
    You said you wanted to be around when I made a mistake; well, this could be it, sweetheart.
Re^2: intersection of N arrays
by Anonymous Monk on Aug 24, 2020 at 02:55 UTC
    This works with numbers, how can you make it work with strings.

      c:\@Work\Perl\monks>perl use strict; use warnings; my %ids; sub intersect { my %count; my @ret; my $count = keys %ids; foreach my $key (keys %ids) { my %this; for (@{$ids{$key}}) { next if $this{$_}; $count{$_}++; $this{$_}++; if ($count{$_} == $count) { push @ret, $_; } } } undef %ids; return @ret; } $ids{'foo'} = [ qw(three four four five) ]; $ids{'bar'} = [ qw(three) ]; $ids{'zoo'} = [ qw(five four three) ]; print "[ ",join(', ',intersect)," ]\n"; __END__ [ three ]


      Give a man a fish:  <%-{-{-{-<