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

Replies are listed 'Best First'.
Re^3: append files to a directory
by choroba (Cardinal) on Feb 21, 2018 at 09:34 UTC
    You must include the path in the file name:
    my $outputfile = "${str}output_$key";

    BTW, if you want to keep the name of the directory in a variable, don't call it $str, call it $dir. And use it everywhere. So, you can replace

    mkdir("dict"); my $str="dict/"; opendir(DIR,$str);

    with

    mkdir my $directory_name = 'dict' or die $!; opendir my $dir_handle, $directory_name or die $!; ... my $outputfile = "$directory_name/output_$key";

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re^3: append files to a directory
by shmem (Chancellor) on Feb 21, 2018 at 09:54 UTC
    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'