in reply to foreach not working as I expected

You need to move the print ADDTO line inside the foreach loop - all you're doing there is sequentially opening the files one after the other.

It's not possible to open more than one file per filehandle - hence the handle is getting reassigned each time the loop iterates. This is why you get output in one file but not the others.

It's also good practice to close each file when you're done appending, even though the file will be closed when the filehandle goes out of scope.

A quick rewrite of your loop gives:

foreach my $file (<*.txt>) { open ADDTO, $file or die "Couldn't open $file for append.\n"; print ADDTO $txt; close ADDTO; }

This should give you what you expect.

Hope that helps ..
-- Foxcub

Update: Added "or die" to the open.

Replies are listed 'Best First'.
Re: Re: foreach not working as I expected
by Jenda (Abbot) on Dec 18, 2002 at 22:18 UTC

    Well you can "open" several fields into one filehandle. Using some tie() magic. See IO::Tee on CPAN.

    But unless you really need to keep printing to several places at once i would not recomend this. If you only need to print a single thing into the files it's better to open+print+close them in the loop.

    Jenda