in reply to foreach not working as I expected

Put the actions you want to do to the file inside the loop. And don't forget to close the file when done.

#!C:\Perl\bin\perl.exe #Lou M 121702 @ GW use warnings ; use diagnostics ; use strict ; my $txt = "Windows 2000 SP3\nWindows Office XP\n" ; foreach my $file (<*.txt>) #For Each .txt file #in the directory #this script runs from { open ADDTO, ">> $file" or die "Can't open file: $!" ; print ADDTO $txt; #Write the text close ADDTO; } print "Done\n\n" ; #Let the user know it is done
--- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';

Replies are listed 'Best First'.
Re: Re: foreach not working as I expected
by chromatic (Archbishop) on Dec 18, 2002 at 18:09 UTC
    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. :)

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