G'day Anupam,

This does what you asked for:

#!/usr/bin/env perl use strict; use warnings; use autodie; use List::Util qw{max}; use Tie::File; my $master_list = 'pm_1079097_List'; my @files = qw{pm_1079097_File1 pm_1079097_File2 pm_1079097_File3}; tie my @list, 'Tie::File', $master_list; my %matrix = map { $_ => {} } @list; untie @list; for my $filename (@files) { tie my @file, 'Tie::File', $filename; for (@file) { $matrix{$_}{$filename} = 1 if exists $matrix{$_}; } untie @file; } my $format = '%' . max(map length, keys %matrix) . 's' . ((' %' . max(map length, @files) . 's') x @files) . "\n" +; printf $format, '', @files; for my $gene (sort keys %matrix) { printf $format, $gene, map { $_ || 0 } @{$matrix{$gene}}{@files}; }

Output:

pm_1079097_File1 pm_1079097_File2 pm_1079097_File3 Gene1 1 0 0 Gene2 1 1 0 Gene3 1 1 1 Gene4 0 1 1 Gene5 0 0 1 Gene6 0 0 0

I prefixed the filenames you gave with 'pm_1079097_', replace those with your real filenames. The input data I used should match your sample data: it's shown in the spoiler below.

All code I used is documented in http://perldoc.perl.org/perl.html. If you don't understand something, that you should be the first place you look.

If you have follow-up questions, ensure they're accompanied by code, data, error messages, and so on (marked up appropriately, e.g. within <code>...</code> tags) as described in "How do I post a question effectively?".

-- Ken


In reply to Re: Creating a binary matrix by kcott
in thread Creating a binary matrix by perl_user123

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.