use strict; use warnings; # avoid using $a and $b my $f='figure1 vdfsvh figure3 vdsvjjh'; my $ch='chapter 3 svbjjvfh chapter5'; my @figs = $f =~ /figure\s*(\d+)/g; my %chaps; $chaps{$_}++ for ( $ch =~ /chapter\s*(\d+)/g ); for my $i (@figs) { print "href=\"chapter $i.html#figure $i\">figure $i\n" if exists $chaps{$i}; }