my $book_regex = qr/^Book ref #(\d+)/; # (\d+) will capture the ref into $1 my ($ref, $title, ...); while () { # 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