0

I have some txt files with a huge list of lines like:

file_1.txt        file_2.txt      file_3.txt
XP_001703830.1    XP_001703820.1  XP_001703810.1
XP_001703836.1    XP_001703815.1  XP_001703805.1
XP_001703844.1    XP_001703834.1  XP_001703844.1

let's say that I have 10 or more files in a folder, and I want to read all of them and store the content in a array, I have used this code, but it just store one line of a file, and not all the lines !!

#!/usr/bin/perl -w
use strict;

my @files = glob("*.txt");
my @ID;

for my $file(@files) {
    open IN, '<', $file or die "$!";
        while (<IN>) {
            my $fields = $_;
            push @ID, $fields;
        }
}

foreach (@ID){
    print "$_\n";
}
close IN;
exit;

what I want is store all the lines in a array like:

XP_001703830.1      
XP_001703836.1      
XP_001703844.1      
XP_001703820.1
XP_001703815.1
XP_001703834.1
XP_001703810.1
XP_001703805.1
XP_001703844.1

Thanks So Much !!!

3
  • First close IN; should be under for loop where you are opening a txt file. Commented Feb 27, 2017 at 8:32
  • I am perfectly able to store all the lines in a array using your exact code!! What are you getting in @ID? Commented Feb 27, 2017 at 8:36
  • Why are you reinventing cat? Commented Feb 27, 2017 at 15:31

3 Answers 3

3

If you are anyway reading entire stuff into memory ( not usually the best use of RAM ) then you could do this ... perl TIMTOWTDI

my @ID;
{
    local(@ARGV) =  glob("*.txt");
    @ID=<>;
}
print "@ID\n";
Sign up to request clarification or add additional context in comments.

Comments

1

By initializing default input separator as undef this can be solved,

use strict;
my @files = glob("*.txt");
my @ID;

for my $file(@files) {
    open IN, '<', $file or die "$!";
    while (<IN>) {
        my $fields = do{local $/; <IN>};
        push @ID, $fields;
    }
}

foreach (@ID){
    print "$_\n";
}
close IN;
exit;

Comments

0

I guess you have a problem with line terminators. Try

open IN, '<:crlf', $file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.