Domanda

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

È stato utile?

Soluzione

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" ;

Altri suggerimenti

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!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top