in reply to iterative foreach loop

The hint the warning is giving you is that you're not actually reading from the file and filling the @lines array - see <FILEHANDLE> under I/O Operators and readline. This will also get rid of the warning that the filehandle FILE is only used once. By the way, in modern perl it's better to use lexical filehandles and the three-argument open, as in open my $fh, '<', $filename or die $!;.

Why do you want to use for(;;) instead of foreach or while? The latter is the most common way to read a file line-by-line because it is usually most efficient, and is shown in the above links. (BTW, personally I would write for(;;) instead of foreach(;;).)

Update: For a gentler and shorter introduction, see perlintro, it also has a section "Files and I/O".

Replies are listed 'Best First'.
Re^2: iterative foreach loop
by hchana (Acolyte) on Nov 14, 2017 at 11:23 UTC

    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;

      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).

      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.