-1

I have an input file with

words;
yadda yadda;
keyword 123;
yadda;

and I want to simply get the value 123 saved as a variable. I tried a solution from here:

my $var;
open(FILE,$data.dat) or die "error on opening $data: $!\n";
while (my $line = <FILE>) {
        if (/^keyword/) {
                $var = $1;
                print $line;
                last;
        }
}
close(FILE);

This isn't working and gives me following error: Use of uninitialized value $_ in pattern match (m//) at ./script.pl line 91, <FILE> line 384. (this occurs for all lines of <FILE>)

I found another solution without the if-condition which just states @string = sort grep /^keyword/,<FILE>; and works. Can you please explain to me what is happening here?

/edit

Thx for the answers and explanations! What do you think is the better/more elegant way? The grep or the if-condition?

Community
  • 1
  • 1
EverythingRightPlace
  • 1,197
  • 12
  • 33
  • Your `grep` question is by and large unrelated, in that it doesn't solve this precise problem. One question per question, please; post a separate question if you still want that answered, as you have already accepted an answer here, and thus marked your problem as solved. – tripleee Jul 30 '13 at 14:04

2 Answers2

2

$1 refers to the first capture group, but your regex doesn't contain any capture groups, so it's undefined. Try

if ($line =~ /^keyword\s+(-?(?:\d+|\d*\.\d*)(?:[Ee]-?(?:\d+|\d*\.\d*))?)/) {

Notice also that the regex is being applied to the variable containing the line you just read.

Edit: Updated to cope with numbers in scientific notation. This is a significant additional requirement which you should have specified explicitly in the first place.

tripleee
  • 175,061
  • 34
  • 275
  • 318
2

You need the following change:

if ($line =~ m/^keyword\s+(\d+)/)

Explanation: You read into $line, hence $_ which is the default target for match is undefined. In addition, you'd get another error with $1, because your pattern did not specify a capturing group.

Ingo
  • 36,037
  • 5
  • 53
  • 100