0

Hi This might sound silly, but what I am trying to do is, I want to loop through the array and if it finds the matching pattern in the text file, print md127. otherwise print sda however I don't want it to print sda for each line it cannot find, I only want to print it once and only if it cannot find the matching pattern. Heres the sample of my code:

#open output
open (IN, $output) || die "Cannot open the.$output.file";
my @lines = <IN>;
close IN;

for (@lines)
{ 
     if ($_=~ /$find/ )
     {
             #&md127;
             print "md127\n";
     }
     elsif ($_!~ /$find/)
     { 
             print "sda\n";
     }
}

any help will be appreciated.

2 Answers 2

5
#open output
open (my $IN, "<", $output) || die "Cannot open the.$output.file";
my @lines = <$IN>;
close $IN;

my $foundIt = 0;
for (@lines)
{ 
     if ($_=~ /$find/ )
     {
             #&md127;
             print "md127\n";
             $foundIt = 1;
     }

}

if (! $foundIt)
{
    print "sda\n";
}
Sign up to request clarification or add additional context in comments.

2 Comments

After a successful find you could bail out of the loop with last;. That might speed things up a little bit.
Depends on whether he wants only one "md127". From the question i understood he wanted as many "md127" as there are finds but only a single or none "sda". But yes, if one "md127" is all you need, following $foundIt = 1; with a last; will get you right out of the loop.
2

One possible approach is to set a $found variable, set to 0 initially, and set to 1 if you found what you were looking for.

If at the end of the loop, $found was 0, print "sda":

$found = 0;
for (@lines)
{ 
     if ($_=~ /$find/ )
     {
             #&md127;
             print "md127\n";
             $found = 1;
     }
}

print "sda\n" unless $found;

1 Comment

You were faster. print "sda\n" unless $found though. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.