1

I have 5 files in different directory. I am extracting the data's from all files and make it as new file.

Note: input each file as an array and extract the data by using for loop for each n every files. I want to make it as single for loop to take the files and process the rest

For file1 am using

foreach (@file)
{
    my @temp = split(/\t/, trim($_));
    push(@output, $temp[0] . "\t" . $temp[1] . "\n");
}

foreach(uniq(@output))
{
    print $OUTPUTFILE $_;
}

I am doing this for five times to process five file. Can anyone help me on how to make it simple

3
  • cat file1 file2 file3 | do_things_with_perl.pl Commented May 14, 2014 at 8:34
  • @JohnC, i don't want to use cat. i need to do that in array Commented May 14, 2014 at 8:44
  • 1
    You can put that code in a loop. Commented May 14, 2014 at 8:51

2 Answers 2

1

Just wrap it in an outer loop, iterating over all five files:

for my $file ( @five_files ) {

    open my $fh, '<', $file or die "Unable to open $file: $!";
    my @file = <$fh>;

    foreach (@file) {
        my @temp = split(/\t/, trim($_));
        push(@output, $temp[0] . "\t" . $temp[1] . "\n");
    }

    foreach(uniq(@output)) {
        print $OUTPUTFILE $_;
    }
}

Since you're interested in just the first two elements of @temp, the foreach @file loop can be simplified:

my @temp = split /\t/, trim($_), 2;
push @output, @temp, "\n" ;
Sign up to request clarification or add additional context in comments.

1 Comment

Zaid, my @temp = split /\t/, trim($_), 2; extracting first two rows alone not the first two column element
0

What if you simplify things by flattening out your @file array with join. Then you can just split it up and deal with the list. Eg:

!/usr/bin/perl

my @file = ("file1\tfile3 ","file1\tfile3\tfile3 ","file2");  # Some test data.

my $in = join "\t", @file;  # Make one string.
my @temp = split(" ", $in); # Split it on whitespace.


# Did it work?
foreach(@temp)
{
    print  "($_)\n";  # use () to see if we have any white spaces.
}

Might be a problem if you have spaces in your filenames though!

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.