Ok, here is a suggestion. I consider the if block: if ($check==1 && $dolink ) { ($word, $link ) = get_html_link_info( $name, $word ); print $fh_out qq[$word]; } now I added the get_html_link_info() function: sub get_html_link_info { my ( $dir, $word ) = @_; $word=~s/(\S+)\s*/$1/g; my @dirs = <$dir/rev*>; my $num_dirs = scalar @dirs; if ( $num_dirs != 1) { die "Unexpected directory configuration. Expected single rev* folder, " . "found $num_dirs folder(s)"; } $dir = shift @dirs; my @files = <$dir/*.html>; my $num_files = scalar @files; if ( $num_files != 1) { die "Unexpected directory configuration. Expected single .html file, " . "found $num_files .html files(s)"; } my $link = shift @files; return ($word, $link ) }