Search code examples
loopsperlforeachline-breaks

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!


Solution

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

    print ("\n");
    

    to:

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