in reply to Re^2: append files to a directory
in thread append files to a directory

opendir(DIR,$str);

See opendir. That's for reading a directory.

If you want to write files into a directory, name it. open doesn't guess, and doesn't magically prepend a path component to the file name; opendir doesn't set a directory context for open.

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; }

Better alternative to join, because it is portable (Windows etc):

use File::Spec; ... for my $key (keys %hash){ ... $outputfile = File::Spec->catfile($str,$outputfile); ... }

update:

Re-reading the question and code, it looks like you mistook opendir for chdir which sets the current working directory. Cwd comes in handy:

#!/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 (<DATA>) { 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
perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'