johnirl has asked for the wisdom of the Perl Monks concerning the following question:

Hey Monks
I am looping through a file looking for lines that match a certain regex. How would I then store that line in a variable so I can work with it?.

This is the code I have at the moment

my $line = <DATA>; foreach ($line =~ /regex/){ Do stuff with $line; }

j o h n i r l .

Sum day soon I'Il lern how 2 spelI (nad tYpe)

Replies are listed 'Best First'.
Re: Storing Regex Results
by hotshot (Prior) on Aug 20, 2002 at 09:21 UTC
    I suggest you read more about regexp, coz' this is kind of a basic thing:
    my @array; while ($line = <DATA>) { if ($line =~ /regexp/) { push(@array, $line); } }
    like this you save all the lines that matche your regexp and can work of them. but if you want to save the match result, then:
    my @array; while ($line = <DATA>) { if ($line =~ /(regexp)/) { # surrounding the regexp with brackets push(@array, $1); # holds the result of the match from the last +regexp } }


    Hotshot
      Yeah I know. Thanks Hotshot. I got it just after I pressed the submit button. This wasn't really ment to be the questioned asked. Made a bit of a mistake. :-( The embarrasment.

      j o h n i r l .

      Sum day soon I'Il lern how 2 spelI (nad tYpe)