Hi,

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:

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
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.

In reply to Re: Perl store as variables regex matches for use outside of loop. by Laurent_R
in thread Perl store as variables regex matches for use outside of loop. by john.tm

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.