This is a test version of Biostars. For the public version, visit https://www.biostars.org.
common between in all the coloumns

s1-> a c b s2-> b a c
s3-> a b c s4-> a b c

in the above a,b,c in common in each coloumn s1, s2, s3, s4. but i have s1, s2, s3, s4, s5 coloumn with lakhs of entries. how should i write a perl script to find out the entries are common in all coloumn. plsease suggest me..

perl

1 answer

Defining the problem clearly is always a good place to start whether you are asking for help or solving it yourself.

I'll assume that I understand your problem and offer the following solution:

#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

my %hash;
my $file = shift @ARGV; # YOU MUST SUPPLY THE FILE NAME AS A COMMAND LINE ARGUMENT
open (FILE, $file); 
while (<FILE>) {
    my $column_counter = 0;
    my $line = $_;
    chomp $line;
    my @columns = split("\t", $line);
    foreach (@columns) {
        $column_counter++;
        $hash{$column_counter}{$_} = 1; # CREATES A HASH OF COLUMNS NUMBERED BY POSITION POINTING TO EACH UNIQUE VALUE IN THAT COLUMN 
    }
}
close FILE;
# print Dumper(\%hash); # UNCOMMENTING THIS COMMAND WILL HELP YOU UNDERSTAND THE CODE ABOVE
my @shared;
# LOOP THROUGH UNIQUE VALUES IN COLUMN 1 TO SEE WHICH EXIST IN EVERY OTHER COLUMN
for my $Value (keys $hash{'1'}) { 
    # CHECK TO SEE IF VALUE IS PRESENT IN ALL FIVE COLUMNS
    if ( exists $hash{'2'}{$Value} && $hash{'3'}{$Value} && $hash{'4'}{$Value} && $hash{'5'}{$Value} ) { 
        push(@shared, $Value);
    }
}
my $output = join("\n", @shared);
print "The values shared by all columns are:\n$output";

Hope this helps.

Log in to answer this question.