in reply to Re: foreach not working as I expected
in thread foreach not working as I expected

And don't forget to close the file when done.

If you're going to check the status of the close, that's one thing (and it should be done more), but it's not really necessary if you're opening the same filehandle immediately. Here's a more paranoid version of the loop where I'd close:

for my $file (<*.txt>) { open my $add, '>>', $file or die "Can't open file: $!\n"; print $add $txt; close $add or die "Can't close file: $!\n"; }

Update: Oh yeah, in a long-running program that can be a problem. That's why I prefer to localize the glob or to use lexical filehandles. :)

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

    In this case, since the program is over when the loop completes, that's true. But what if there was more code beyond the end of the loop? If the handle wasn't explicitly closed inside the loop it would remain open.

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
Re: Re: Re: foreach not working as I expected
by mce (Curate) on Dec 19, 2002 at 15:25 UTC
    Why checking on the close :-)

    I always use IO::File and run the filehandle lexically. It gets close automaticly when it runs out of scope as you mention correctly in your update.


    ---------------------------
    Dr. Mark Ceulemans
    Senior Consultant
    IT Masters, Belgium