in reply to Perl store as variables regex matches for use outside of loop.
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
|
|---|