If u have horse instead of A1 lion instead of A2 mule instead of A3 tiger instead of A4 #### __DATA__ horse;tiger lion;mule lion;tiger horse;mule #### use strict; use warnings; my %A; my ($max_row, $max_col) = (4,4); # autovivify interesting rows/cols of %A while () { warn("Line $.: cannot understand: $_") , next unless /(\w+);(\w+)/ +; my ($row, $col) = ($1,$2); $A{$row}{$col}++; $A{$col}{$row}++; # uncomment if relationship is not bidirectional } # print col. header print " "; printf("%-3d",$_) for (1..$max_col); print "\n"; #print matrix A for my $row (1 .. $max_row) { printf("%-3d", $row); for my $col (1 .. $max_col) { printf(" %-3d", exists $A{$row}{$col} ? "1" : "0" ); } print "\n"; } #### printing as 1 2 3 4 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 #### horse lion mule tiger horse 0 0 1 1 lion 0 0 1 1 mule 1 1 0 0 tiger 1 1 0 0