Home > Mobile >  Foreach loop with two lists for corresponding rows (perl)
Foreach loop with two lists for corresponding rows (perl)

Time:09-07

I would like some help in what it seems to be a simple issue in a perl script.

I have two lists as follows. Both have the same amount of rows, and the first row of list1 corresponds to the first row of list2 and so on.

list1

car
ball

list2

30
40

I want to write a perl script to run programs that calls files with names starting with rows of list1. In one of these programs, I have to consider the content of list2, but doing this only for the correspondent row in list1.

This is what I have tried:

perl test.pl list1 list2

test.pl:

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

my $lib = $ARGV[0];
my $cov = $ARGV[1];

chomp $lib;
chomp $cov;

open(INPUT, "$lib");
my @lib = <INPUT>;
close(INPUT);

foreach my $i (@lib){
        chomp ($i);

        `samtools fasta $i\.sorted.bam > $i\.fasta`;
        `jellyfish count -m 80 -L $cov -s 275M -t 10 -C -o $i\.jf $i\.fasta`;
        `jellyfish histo $i\.jf > $i\.histo`;


}

The first program (samtools) is executed correctly, but the second is not because it can't read what is inside variable $cov.

In other words, I would like that option -L from jellyfish count be "30" for "car" and "40" for "ball", but I couldn't make it.

CodePudding user response:

Here is the solution:

#!/usr/bin/perl
use strict; use warnings;

use File::Slurp qw(read_file);
my ($file1, $file2) = ($ARGV[0], $ARGV[1]);

my @file1_lines = read_file($file1);
my @file2_lines = read_file($file2);

if ($#file1_lines == $#file2_lines) {
    foreach my $element (0..$#file1_lines){
        my $lib = $file1_lines[$element]; chomp $lib;
        my $cov = $file2_lines[$element]; chomp $cov;
        
        print "samtools fasta ".$lib."\.sorted.bam > ".$lib."\.fasta\n";
        print "jellyfish count -m 80 -L ".$cov." -s 275M -t 10 -C -o ".$lib."\.jf ".$lib."\.fasta\n";
        print "jellyfish histo ".$lib."\.jf > ".$lib."\.histo\n";
    }
} else {
    print "$file1 and $file2 doesn't have same number of lines\n";
}

Here I have used File::Slurp to read entire content of the file into an array. So you must have File::Slurp Perl module in your environment.

Both the file contents are being stored in a two different arrays called @file1_lines and @file2_lines respectively.

  •  Tags:  
  • perl
  • Related