for my $key (keys %hash){ my $outputfile = "output_$key"; $outputfile =~ s{/}{-}g; $outputfile = join '/', $str,$outputfile; # <---- this is missing print "Writing to $outputfile\n"; open OUT,'>',$outputfile or die "Could not open $outputfile : $!"; print OUT $hash{$key}; close OUT; }