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

is there anyway to go through each line of a file using the foreach loop?

Replies are listed 'Best First'.
Re: foreach loop
by LTjake (Prior) on Aug 27, 2002 at 14:43 UTC
    open (MYFILE, "< $filename") or die "Failed to open $filename: $!"; @rows = <MYFILE>; close (MYFILE); foreach $row (@rows) { # do something to $row }
    It's better not to slurp the file:
    open (MYFILE, "< $filename") or die "Failed to open $filename: $!"; while (<MYFILE>) { # do something with $_ } close (MYFILE);
Re: foreach loop
by insensate (Hermit) on Aug 27, 2002 at 14:44 UTC
    Yes...but there's a cleaner way...
    Open your file:
    open(IN,"myfile.txt");

    Create a while loop using the line operator on the filehandle you've just created:
    while(<IN>){ each line of your file is iterated over... the contents of each line are stored in the variable $_ }
Re: foreach loop
by fglock (Vicar) on Aug 27, 2002 at 14:41 UTC

    foreach (<FILE>) { ... }