EverythingRightPlace
EverythingRightPlace

Reputation: 1197

Quit while-loop if statement is true

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.

Upvotes: 0

Views: 262

Answers (3)

AViYahu
AViYahu

Reputation: 1

You can add the regexp evaluation to the while loop condition, without using return or last.

sub check_file {
    open(FILE, "stuff.dat") or die;

    my $result;
    my $line;

    while (($line = <FILE>) && ($result = ($line !~ m/regex/))) {};

    close(FILE);
    ## $result equals 1 only if we have exit the loop and 
    ## didn't have a match till the last line of the file
    return ($result != 1);
}

Upvotes: 0

mpapec
mpapec

Reputation: 50637

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!";

Upvotes: 1

Sakthi Kumar
Sakthi Kumar

Reputation: 3045

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

Hope this helps.

Upvotes: 0

Related Questions