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

Hi,
I have a question about grepping a file to match a regex, and then using the "match" as a variable in some other function.
The code I have so far is:
#!/usr/bin/perl use strict; use warnings; my $file = "./file.txt"; # File data looks like: (without the beginning hash) # tag: variable open(FILE, $file); if ( grep /^tag\: (.*)$/, <FILE> ) { print "Found tag: $1\n"; } # end-if close(FILE); exit;
My question is, how can i use what the match of (.*) was? $1 is not it.
Any help would be appreciated.
Cheers,
Reagen

Update: Sorry, looks like some more info is needed.
There could be 0 or 1 matches in the file (i.e. either there is a tag and value or there isnt).

Replies are listed 'Best First'.
Re: use regex match from file grep
by Joost (Canon) on Jun 11, 2004 at 10:03 UTC
    What do you want it to be? Grep loops over all of the input, so the only thing that makes sense (to me) is the last match:

    my $last_match; if ( grep { /^tag\: (.*)$/ and $last_match = $1 and 1} <FILE> ) { print "Found tag: $last_match\n"; }

    more likely you want all matches:

    while (<FILE>) { next unless /^tag\: (.*)$/; print "Found tag: $1\n"; }

    edit: or even

    print map /^tag\: (.*)$/ ? "Found tag: $1\n" : (), <FILE>;

    Hope this helps,
    Joost.
      Thanks Joost.

      Example 1 does the trick :)

      Cheers,
      Reagen
Re: use regex match from file grep
by delirium (Chaplain) on Jun 11, 2004 at 12:16 UTC
    This is a great job for a one-liner and the post-match variable:

    perl -ne "print $' if /^tag\: /" file.txt