package Sublist; use strict; use warnings; use v5.22; use Exporter qw; our @EXPORT_OK = qw; sub a_within_b { # assume @a <= @b my ($a, $b) = @_; my @a = @{$a}; my @b = @{$b}; # check to see if first element of @a is in @b # @idx is array that stores all indexes of @b where first element of @a is in @b my @idx = grep { $b[$_] eq $a[0] } 0 .. $#b; return 0 unless (@idx); # first element of @a not found anywhere in @b foreach my $i (@idx) { # loop through each index of @b we found # skip if the first element of @a occurs too near the end of @b # (i.e. the remaining elements of @a won't fit in @b) next if ($i > scalar @b - scalar @a); # $match counts number of matches of @a in @b. Start at 1 since we already # know that the first element of @a was found in @b my $match = 1; # sequentially loop through remaining elements of @a to see if they # appear in order in @b for (my $a_idx=1, my $b_idx=$i+1; $a_idx<=$#a; $a_idx++, $b_idx++) { $match++ if ($a[$a_idx] eq $b[$b_idx]); } # number of matches has to eqal number of elements in @a return 1 if ($match == scalar @a); } return 0; } sub compare_lists { my ($args) = @_; my @a = @{$args->{listOne}}; my @b = @{$args->{listTwo}}; return "equal" if (@a == 0 && @b == 0); # empty lists return "sublist" if (@a == 0 && @b > 0); # empty list within non empty list return "superlist" if (@a > 0 && @b == 0); # non empty list contains empty list return "equal" if (@a == @b && a_within_b(\@a, \@b)); return "superlist" if (@a > @b && a_within_b(\@b, \@a)); return "sublist" if (a_within_b(\@a, \@b)); return "unequal"; } 1;