#!/usr/bin/perl -w use strict; my %Isbn2Title; while () { next unless (my $ISBN = (m/\|a\s+(\d{13})/)[0]); my $title = get_title(); $title =~s/\s+$//; #delete trailing whitespace ${Isbn2Title}{$ISBN}=$title; } foreach my $isbn (sort keys %Isbn2Title) { print "ISBN=$isbn title=$Isbn2Title{$isbn}\n"; } #Prints: ISBN=9780470086223 title=Heads in the sand sub get_title { while () { my $title = (m/\|a\s+(.*?)[\|:]/)[0]; return $title if $title; } } __DATA__         020 |a 9780470086223 (hardback)         24510 |a Heads in the sand : |b how the Republicans screw up foreign policy and foreign policy screws up the Democrats / |c Matthew Yglesias         24610 |a How the Republicans screw up foreign policy and foreign policy screws up the Democrats         61020 |a Democratic Party (U.S.)