Serendipity
Serendipity

Reputation: 49

Perl: Adding an exception to a foreach loop

I'm new to Stack Overflow and I would like to ask for some advice with regard to a minor problem I have with my Perl code. In short, I have written a small programme that opens text files from a pre-defined array, then searches for certain strings in them and finally prints out the line containing the string.

my @S1A_SING_Files = (
    'S1A-001_SING_annotated.txt', 
    'S1A-002_SING_annotated.txt',
    'S1A-003_SING_annotated.txt', 
    'S1A-004_SING_annotated.txt',
    'S1A-005_SING_annotated.txt'
    );

foreach (@S1A_SING_Files) {
    print ("\n");
    print ("Search results for $_:\n\n");   
    open (F, $_) or die("Can't open file!\n");

        while ($line = <F>) {
        if ($line =~ /\$(voc)?[R|L]D|\$Rep|\/\//) {
        print ($line);

        }
    }
}

close (F);

I was wondering whether it is possible to create an exception to the foreach loop, so that the line containing

print ("\n");

not be executed if the file is $S1A_SING_Files[0]. It should then be normally executed if the file is any of the following ones. Do you think this could be accomplished?

Thank you very much in advance!

Upvotes: 2

Views: 179

Answers (3)

ikegami
ikegami

Reputation: 385647

If the array contains unique strings, you can use the following:

print("\n") if $_ ne $S1A_SING_Files[0];     # Different stringification than 1st element?

The following will work even if the array contains non-strings or duplicate values (and it's faster too):

print("\n") if \$_ != \$S1A_SING_Files[0];   # Different scalar than 1st element?

Both of the above could fail for magical arrays. The most reliable solution is to iterate over the indexes.

for my $i (0..$#S1A_SING_Files) {
   my $file = $S1A_SING_Files[$i];

   print("\n") if $i;                        # Different index than 1st element?

   ...
}

Upvotes: 1

Polar Bear
Polar Bear

Reputation: 6798

Your code can be written in following form

use strict;
use warnings;

my @S1A_SING_Files = (
    'S1A-001_SING_annotated.txt', 
    'S1A-002_SING_annotated.txt',
    'S1A-003_SING_annotated.txt', 
    'S1A-004_SING_annotated.txt',
    'S1A-005_SING_annotated.txt'
    );

foreach (@S1A_SING_Files) {
    print "\n" unless $_ ne $S1A_SING_Files[0];
    print "Search results for $_:\n\n";
    open my $fh, '<', $_ or die("Can't open file!\n");
    m!\$(voc)?[R|L]D|\$Rep|//! && print while <$fh>;
    close $fh;
}

Upvotes: -1

toolic
toolic

Reputation: 62037

Yes. Just add a check for the first file. Change:

print ("\n");

to:

print ("\n") if $_ ne $S1A_SING_Files[0];

Upvotes: 1

Related Questions