0

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.

3 Answers 3

1
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!";
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately this leaves the FILE filehandle open once the sub has finished. That could be solve by using lexical filehandles.
0
open(FILE, "stuff.dat")
my $var;
while (my $line = <FILE>){
   if ($line =~ /regex/) {
      $var = $1;
      last;
}
}
close(FILE);
return $var;

Hope this helps.

1 Comment

This isn't working if the regex isn't matched. And this was the behaviour I wanted to avoid.
0

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);
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.