Commonly, we use hashes for doing this sort of work, where you want to have a key (book ref) that holds information about the thing (the book's title). In this specific case, I've used a hash of hashes (HoH), and used regex capture groups (()) to grab the relevant parts of the regex to store. Here's a basic example. This assumes that the book's ref will always be in the same position (above the line containing the title, and any other items you want to store)

#!/usr/bin/perl use strict; use warnings; my %books; my $book_ref; while (<DATA>) { chomp; if (/^\s*book ref #(\d+)/i and $1){ $book_ref = $1; $books{$book_ref} = {}; } if (/^title\s+(.*)$/i and $1){ $books{$book_ref}{Title} = $1; } } # print the whole shebang for my $ref (keys %books){ for my $book_element (keys $books{$ref}){ print "Book ref: $ref, $book_element: $books{$ref}{$book_eleme +nt}\n"; } } # print one of the book's titles print "$books{9969}{Title}\n"; __DATA__ Book ref #4346 Lent: Sun Jul 12 03:26:43 BST 2015 status Lent Description: classic title blah blah blah last used: 2 color red Pages 238 Publisher Bca Type Hardback Location: N/a Author R jones Book ref #9969 Lent: Sun Jul 12 03:26:43 BST 2015 status Lent Description: classic title My Little Pony last used: 2 color red Pages 238 Publisher Bca Type Hardback Location: N/a Author R jones __END__ Book ref: 4346, Title: blah blah blah Book ref: 9969, Title: My Little Pony My Little Pony

-stevieb


In reply to Re: Perl store as variables regex matches for use outside of loop. by stevieb
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.