in reply to Re: iterative foreach loop
in thread iterative foreach loop

Thanks for the information and links - I will read. I have changed my script (see below), is this the best way.?

open (my $in, "<", "TEXT2.txt") or die "Can't open input.txt: $!"; while (<$in>) { # assigns each line in turn to $_ print "$_"; # print contents of $_ line by line } close $in;

Replies are listed 'Best First'.
Re^3: iterative foreach loop
by haukex (Archbishop) on Nov 14, 2017 at 11:29 UTC

    Yes, looks ok to me. Just two minor nitpicks: note the difference between the filenames TEXT2.txt and input.txt, error messages might be a little confusing, so I'd recommend putting the filename in a variable and saying open(my $fh, '<', $filename) or die "Can't open $filename: $!";. Also, and this is very minor, you don't have to put $_ in quotes. For clarity, you could also use a named variable instead of $_, as in while (my $line = <$in>) { print $line; } (Update: I just saw that Laurent_R showed this as well).

Re^3: iterative foreach loop
by 1nickt (Canon) on Nov 14, 2017 at 13:56 UTC

    That's fine, subject to the hints haukex provided.

    Now that you understand the diamond operator (perlop: IO Operators) you can use a modern tool to do the busywork of opening and closing files, character encoding, removing new line characters, error handling, etc.

    use strict; use warnings; use feature 'say'; use Path::Tiny; # imports path() my $filename = '/TEXT2.txt'; say for path( $filename )->lines_utf8({ chomp => 1 }); __END__

    See also:

    Hope this helps!


    The way forward always starts with a minimal test.