opendir(DIR,$str); #### 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; } #### use File::Spec; ... for my $key (keys %hash){ ... $outputfile = File::Spec->catfile($str,$outputfile); ... } #### #!/usr/bin/perl use strict; use warnings; use Cwd; my %hash=(); # input # my $inputfile = 'nv.txt'; # open IN, '<',$inputfile # or die "Could not open $inputfile : $!"; # we use the text after __DATA__ for input while () { my ($key, $val) = split (/:/,$_,2); $hash{$key} .= $val; } # output my $dir = "dict"; -d $dir or mkdir $dir; my $cwd = getcwd(); # from Cwd imported above chdir $dir; # go into directory 'dict' for my $key (keys %hash){ my $outputfile = "output_$key"; $outputfile =~ s{/}{-}g; print "Writing to $outputfile\n"; open OUT,'>',$outputfile or die "Could not open $outputfile : $!"; print OUT $hash{$key}; close OUT; } chdir $cwd; # change directory back __DATA__ test/right/case1:12: //comment test/right/case1:344: //comment test/wrong/case3:123: //comment Output expected: test/right/case1: 12: //comment :344: // comment test/wrong/case3:123: //comment