tags:

views:

91

answers:

2

Could someone provide a good /nice solution in Perl for comparing 2 arrays (a and b) which check if every element on array a is found in array b (and found only once in array b)?

+1  A: 

Do you care if and item is b that not in a? The way you have it phrased b can have more items than a. Also, you need to specify what happens when an item is duplicated in an array. Here is some code that finds if there is at least one of every item in a in b:

#!/usr/bin/perl

use strict;
use warnings;

sub all_in_second {
    my ($first, $second) = @_;
    my %in_second        = map { $_ => 1 } @$second;

    for my $item (@$first) {
        return 0 unless $in_second{$item};
    }
    return 1;
}

my @a = (1, 2, 3, 3, 4);
my @b = (1, 2, 3, 4, 5);

print all_in_second(\(@a, @b)) ? "true" : "false", "\n";

@a = (1, 2, 3, 3, 6);
@b = (1, 2, 3, 4, 5);

print all_in_second(\(@a, @b)) ? "true" : "false", "\n";
Chas. Owens