Exit the while loop if the statement is true

advertisements

I have a subfunction and inside of it I am reading a file in Perl with the usual while-loop line-by-line because that's the only (and best?) option I know in Perl so far. Now I am searching line-based for a keyword with a loop like

my $var;
open(FILE, "stuff.dat")
while (my $line = <FILE>){
   if ($line =~ /regex/) {
      $var = $1;
      return $var;
   } else {
      return "var is not defined!";
   }
}
close(FILE);

but even when it gets the keyword and $var is specified, it gets overwritten on the next line. So I want to quit the while-loop if the keyword is found and $var is defined.

I tried next if or next unless or the last-exit but this isn't working properly and perldoc states that we can't use last for subs.


open(my $FILE, "<", "stuff.dat") or die $!;
while (my $line = <$FILE>){
   if ($line =~ /regex/) {
      return $1 if defined $1;
   }
}
close($FILE);
return "var is not defined!";