Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I have two arrays of equal size and want to simply print an element from each array to a new output file. e.g. $array1[[0]] and $array2[[0]] to a new file etc...

I thought this would work (below) but i'm only creating one new file. Where am I going wrong? Thanks!

for (my $i=0; $i<@array1; $i++) { open (OUT, ">$$.out") or die "can't open OUT\n"; print OUT ">$array1[$i]>$array2[$i]\n\n\n"; }

Edit by BazB: add code tags around arrays.

Replies are listed 'Best First'.
Re: printing to new output files within a loop
by Old_Gray_Bear (Bishop) on Dec 20, 2004 at 21:01 UTC
    Try adding the index to the file name and closing the file inside the loop. Right now you are over-writing the file each time.
    for (my $i=0; $i<@array1; $i++) { open (OUT, ">$$.out.$i") or die "can't open OUT\n"; print OUT ">$array1[$i]>$array2[$i]\n\n\n"; close(OUT) or die "Close error on $$.out.$i -- $!\n"; }

    ----
    I Go Back to Sleep, Now.

    OGB

Re: printing to new output files within a loop
by Sandy (Curate) on Dec 20, 2004 at 20:59 UTC
    the $$ variable is a process id, which does not change within a currently running process (i.e. execution of your code)

    If you want a different file name for each iteration, you could construct one using the $i variable, as well as the $$. Don't forget to close the file after you're done!

    i.e.

    for my $i (0..@array1-1) { open (OUT,">$$.out$i", or die "Ooops...!"; print OUT ">$array1[$i]>$array2[$i]\n\n\n"; close OUT; }

Re: printing to new output files within a loop
by rir (Vicar) on Dec 20, 2004 at 21:12 UTC
Re: printing to new output files within a loop
by amw1 (Friar) on Dec 20, 2004 at 20:56 UTC
    Looks like you're opening a file named <pid>.out. This may work for you. ($$ is the current process id)
    for (my $i = 0 ; $i < @array1 ; $i++) { open(OUT, ">$i.out") or die "can't open $i.out: $!\n"; print OUT ">" . $array1[$i] . ">" . $array2[$i] . "\n\n\n"; close OUT; }
Re: printing to new output files within a loop
by hostyle (Scribe) on Dec 20, 2004 at 22:11 UTC

    Are you sure you didn't mean $_ as opposed to $$ ? $$ Is the pid of your current process which will not change during your loop, hence only one file. $_ is the current default value of your iteration. Or perhaps you meant $i?