use IO::File (); ## local $/; # you're not using this my $fh = IO::File->new(); # declare this just once foreach $file (sort keys %altnames) { my ($hr_title) = ( $file =~ m/(.*)\.txt/ ); print "

$hr_title

\n"; # don't need parens for print ... $fh->open( "$dir/$file" ) or die $!; # you gotta check! while (<$fh>) { print; } $fh->close; }