Skip to content

Instantly share code, notes, and snippets.

@putnamhill
Last active January 11, 2018 00:42
Show Gist options
  • Save putnamhill/66fb420686762c66252c533b282c5570 to your computer and use it in GitHub Desktop.
Save putnamhill/66fb420686762c66252c533b282c5570 to your computer and use it in GitHub Desktop.
Print items of in-list that are not in other-list; i.e. the relative complement of in-list and other-list.
#!/usr/bin/perl -w
use Getopt::Long;
# use diagnostics;
sub usage {
my $name = $0;
$name =~ s/.*\///;
print <<EOT;
Usage: $name [options] in-list other-list
Print items of in-list that are not in other-list; i.e. the relative complement of in-list and other-list.
If other-list is not specified we automatically read from stdin by using the <> construct.
Options:
-h, --help: print this message
-i, --intersection: list the intersection of the 2 lists rather than the default relative compliment
EOT
}
BEGIN {
my $help;
our $intersection;
GetOptions(
'help' => \$help,
'h' => \$help,
'intersection' => \$intersection,
'i' => \$intersection
);
defined $help and usage and exit;
our %in_list=();
# load the hash using new items as keys
my $in_list_file = shift;
not defined $in_list_file and usage and exit;
open(IN_LIST, $in_list_file) or die "Could not open in_list file: $in_list_file: $!";
while (<IN_LIST>) {
chomp;
$in_list{$_} = 0;
}
close(IN_LIST);
}
while (<>) {
chomp;
$in_list{$_}++ if exists $in_list{$_};
}
END {
my $count;
my @result_list = ();
while ( my ($item, $member_of_both_lists) = each(%in_list) ) {
if (defined $intersection) {
$member_of_both_lists and push(@result_list, $item);
} else {
$member_of_both_lists or push(@result_list, $item);
}
}
$count = $#result_list + 1;
if ($count) {
foreach (@result_list) { print "$_\n"; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment