Question

How can I add a counter to this statement.

# go through each reference file
for my $file (@reference_files) 
{
    open my $ref, "<", $file or die "Can't open reference file '$file': $!";
    while (my $line = <$ref>) 
    {
        chomp $line;
        my ($scaffold, undef, $type, $org_snp, $new_snp, undef, undef, undef, $info) = split /\t/, $line;
        next if not $scaffold =~ /^KB/;
        next if not $type =~ /^GENE/i;

        my ($transcript_id, $gene_name, $auto) = split /[;][ ]/, $info;
        $gene_name = $1 if $gene_name =~ /["]([^"]*)["]/;

        if (my $matching_genes = $genes{$scaffold}) 
        {
            say join "\t", $gene_name, $_ for values %$matching_genes;
        }
    }

    say "###";
}

I would like the script to additionally count all $matching_genes. Is there a way to incorporate this? I've been unsuccessful with standard counters (i.e. $i++) as it's pulling all values in the hash.

Was it helpful?

Solution

You can have a global counter variable on the top intialized to 0 before your for loop, say:

my $counter = 0;

# go through each reference file
for my $file (@reference_files)
# ... Rest of your code ...

Then, you can increment $counter inside of the if statement where $matching_genes is assigned:

if (my $matching_genes = $genes{$scaffold}) 
{
        $counter++;
        say join "\t", $gene_name, $_ for values %$matching_genes;
}

OTHER TIPS

my $count=0;
# go through each reference file
for my $file (@reference_files) 
{
    open my $ref, "<", $file or die "Can't open reference file '$file': $!";
    while (my $line = <$ref>) 
    {
        chomp $line;
        my ($scaffold, undef, $type, $org_snp, $new_snp, undef, undef, undef, $info) = split /\t/, $line;
        next if not $scaffold =~ /^KB/;
        next if not $type =~ /^GENE/i;

        my ($transcript_id, $gene_name, $auto) = split /[;][ ]/, $info;
        $gene_name = $1 if $gene_name =~ /["]([^"]*)["]/;

        if (my $matching_genes = $genes{$scaffold}) 
        {
            say join "\t", $gene_name, $_ for values %$matching_genes;
            $count =+ scalar(keys %$matching_genes);
        }
    }

    say "###";
}
print "total: $count\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top