Skip to content

Instantly share code, notes, and snippets.

@Osse
Created August 23, 2012 16:41
Show Gist options
  • Save Osse/3438510 to your computer and use it in GitHub Desktop.
Save Osse/3438510 to your computer and use it in GitHub Desktop.
Find duplicates redux
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
# Notice that the values are all equal for some of the keys
my @stuff = ( { a => "1", b => "2", c => '4'},
{ a => "1", b => "3", c => '4'},
{ a => "1", b => "2", c => '4'},
{ a => "1", b => "2", c => '4'}
);
my @keys;
my @dups;
@keys = keys $stuff[0];
say 'All the keys in @stuff:';
for(@keys) { print "$_ "; }
say '';
@dups = grep {
my $bool;
for (my $i = 0; $i < scalar(@stuff)-1; $i++) {
$bool = $stuff[$i]{$_} eq $stuff[$i+1]{$_};
last if not $bool;
}
$bool;
} @keys;
say "The keys for which all values are equal:";
for(@dups) { print "$_ "; }
say '';
@smujohnson
Copy link

!/usr/bin/perl

use strict;
use warnings;

use feature 'say';

Notice that the values are all equal for some of the keys

my @stuff = (
{ a => "1", b => "2", c => '4'},
{ a => "1", b => "3", c => '4'},
{ a => "1", b => "2", c => '4'},
{ a => "1", b => "2", c => '4'},
{ a => "1", b => "2", c => '4', d => '2'},
);

my %hash_count;

foreach my $ref_row (@stuff) {
foreach my $key_letter (keys %$ref_row) {
$hash_count{$key_letter}{ $ref_row->{$key_letter} }++;
}
}

my @keys_total = keys %hash_count;
say "All the keys in @stuff: @keys_total";

my @keys_equal;
foreach my $key_letter (keys %hash_count) {
if (keys %{ $hash_count{$key_letter} } == 1) {
push @keys_equal, $key_letter;
}
}

say "The keys for which all values are equal: @keys_equal";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment