I created 200 text files. Each file contained 30 thousand rows and 1 column. I wanted the quickest, easiest way to build a matrix that had 30 thousand rows and 200 columns. I am sure many of you here can do this in less than 10 minutes, and if you are one of them, I would be grateful if you could please share your ideas on other ways to do this or modules I can use, and I also hope somebody out there finds this code easy and useful.
#! usr/bin/perl
#This script takes multiple files that contain the same number of rows
+,
#and builds a matrix where the number of columns would equal the numbe
+r of files.
use warnings;
use strict;
#opens all txt files in the current directory
#and stores the names of the files in @files array
opendir(FILES,".")||die "Cannot open files in the directory\n";
my @files=();
my @matrix=();
for(readdir(FILES)){
if($_=~/\.txt/){
push(@files, $_);
}
}
my $n=scalar(@files);
print "This directory contains $n \.txt files\n";
#opens a file which will contain all the ratios
open(TREE,">matrix.txt");
#goes through each file in @files array
for my $i(0..$#files){
print "Working on \.\.\. $files[$i]\.\n";
open(FH,"<$files[$i]");
my $j=0;
while(my $line=<FH>){
chomp $line;
my @line=split("\t",$line); #This is more applicable if the fi
+le contained more than one column, tab delimited
#@matrix is an array of array
#jth array in @matrix contains records from different files fo
+r jth line
push @{$matrix[$j]}, "$line[0]";
$j++;
}
}
for my $tmp(@matrix){
#$records joins the elements by tab
my $records=join "\t", @$tmp;
print TREE "$records\n";
}
exit;
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.