Skip to content

Instantly share code, notes, and snippets.

@wopfel
Last active August 14, 2018 14:45
Show Gist options
  • Save wopfel/a20a30b6a9ce131f3428de7d11e7529e to your computer and use it in GitHub Desktop.
Save wopfel/a20a30b6a9ce131f3428de7d11e7529e to your computer and use it in GitHub Desktop.
Show a=b data from text lines as grid / matrix

Show data as grid / matrix

Assuming you have an input file like this one ...

horse	green
horse	blue
dog	green
dog	red
dog	yellow
dog	black
cat	red
cat	blue
cat	black
bird	green
bird	blue
bird	red
bird	black
hedgehog	black
hedgehog	green
hedgehog	red
hedgehog	yellow
hedgehog	cyan
rabbit	black
rabbit	green
rabbit	yellow
rabbit	cyan

you can easily get a 2-dimensional array like this (a-values on the left, showing b-matches on the right):

% perl datatest.pl
bird      :  black  blue        green  red          
cat       :  black  blue               red          
dog       :  black              green  red  yellow  
hedgehog  :  black        cyan  green  red  yellow  
horse     :         blue        green               
rabbit    :  black        cyan  green       yellow  

Or this one (b-values on the left, showing a-matches on the right):

black     :  bird  cat  dog  hedgehog         rabbit  
blue      :  bird  cat                 horse          
cyan      :                  hedgehog         rabbit  
green     :  bird       dog  hedgehog  horse  rabbit  
red       :  bird  cat  dog  hedgehog                 
yellow    :             dog  hedgehog         rabbit
#!/usr/bin/perl
use strict;
use warnings;
my @lines = <DATA>;
chomp @lines;
my ( %a, %b, %matrix );
foreach my $line ( @lines ) {
# print $line;
my @field = split /\t/, $line;
$a{ $field[0] }++;
$b{ $field[1] }++;
$matrix{ $field[0] }{ $field[1] } = 1;
}
foreach my $a ( sort keys %a ) {
printf "%-10s: ", $a;
foreach my $b ( sort keys %b ) {
if ( defined $matrix{$a}{$b} ) {
print $b;
} else {
print " " x length($b);
}
print " ";
}
print "\n";
}
print "\n";
foreach my $b ( sort keys %b ) {
printf "%-10s: ", $b;
foreach my $a ( sort keys %a ) {
if ( defined $matrix{$a}{$b} ) {
print $a;
} else {
print " " x length($a);
}
print " ";
}
print "\n";
}
__DATA__
horse green
horse blue
dog green
dog red
dog yellow
dog black
cat red
cat blue
cat black
bird green
bird blue
bird red
bird black
hedgehog black
hedgehog green
hedgehog red
hedgehog yellow
hedgehog cyan
rabbit black
rabbit green
rabbit yellow
rabbit cyan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment