in reply to Perl store as variables regex matches for use outside of loop.
you've been given good answers (use of $1 for retrieving the capture, etc.), I would just add a couple of comments on your code.
If I understand what you are trying to do, your regex matching attempts should be within the loop over the DATA section, not before.
Then, for a regex to capture what it matches or part thereof, you need to use parentheses around the part of the match that you want to capture.
Finally, and less importantly, you might want to consider using the qr// operator (see http://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators) rather than simple quote marks for defining your regex patterns.
Putting it together, you might end up with something like this:
This will work if you are looking at only one book at a time. As mentioned previously by stevieb, you'll probably want to use a hash of hashes if you need to look at several books and store the results for further use.my $book_regex = qr/^Book ref #(\d+)/; # (\d+) will capture the ref in +to $1 my ($ref, $title, ...); while (<DATA>) { # you may need to chomp the lines $ref = $1 if /$book_regex/; $title = $1 if /^title\s+(.*)/; # other regexes for title, etc. } # now you can use $ref and $title
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl store as variables regex matches for use outside of loop.
by 1nickt (Canon) on Jul 12, 2015 at 16:26 UTC | |
by Laurent_R (Canon) on Jul 12, 2015 at 17:50 UTC |