Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

iterative foreach loop

by hchana (Acolyte)
on Nov 14, 2017 at 10:16 UTC ( [id://1203349]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, I'm trying open Text2.txt file and saving contents of each line into an array. I then wish to print each line of the array whilst keeping count of the array length. But this script is not working.? what am I doing wrong.? I am a complete novice, so please could I have simple to understand suggestions. thank you.

#!\usr\bin perl use warnings; use strict; use diagnostics; use feature 'say'; open(FILE, "Text2.txt") or die; my @lines; foreach (my $i = 0; $i < @lines; $i++) { say $lines[$i]; } Error message: Name "main::FILE" used only once: possible typo at open.pl line 9 (#1) (W once) Typographical errors often show up as unique variable nam +es. If you had a good reason for having a unique name, then just menti +on it again somehow to suppress the message. The our declaration is provided for this purpose. NOTE: This warning detects symbols that have been used only once s +o $c, @c, %c, *c, &c, sub c{}, c(), and c (the filehandle or format) are con +sidered the same; if a program uses $c only once but also uses any of the +others it will not trigger this warning.

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

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

      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.
Re: iterative foreach loop
by Laurent_R (Canon) on Nov 14, 2017 at 11:28 UTC
    Hi hchana,

    One possible solution relatively close to yours:

    #!\usr\bin perl use warnings; use strict; use diagnostics; use feature 'say'; open my $FILE, "<", "Text2.txt" or die; # Three-argument syntax +for open my @lines = <$FILE>; # actually reading the file into the a +rray foreach my $line (@lines) { # iterating directly over the @lines a +rray items say $line; # note that your lines already have an + end of line, you would probably prefer to use print rather than say } close $FILE;
    But if all you want to do is to print the lines, then you don't need to store the file in an array: you can read the lines one by one and print them.
    #!\usr\bin perl use warnings; use strict; use diagnostics; open my $FILE, "<", "Text2.txt" or die; while (my $line = <$FILE>) { print $line; } close $FILE;
    The while loop could be boiled down to one line with a statement modifier:
    open my $FILE, "<", "Text2.txt" or die; print while <$FILE>;
    In fact it can be even simpler, using the fact that print provides a list context to the <...> operator:
    open my $FILE, "<", "Text2.txt" or die; print <$FILE>;
Re: iterative foreach loop
by thanos1983 (Parson) on Nov 14, 2017 at 11:38 UTC

    Hello hchana,

    I would approach it like this:

    #!/usr/bin/perl use strict; use warnings; use feature 'say'; my $file = 'file1.txt'; open (my $in, "<", $file) or die "Can't open $file: $!"; while (<$in>) { # assigns each line in turn to $_ chomp; next if /^\s*$/; # skip blank lines say "Line number: " . $. . " Content of line: " . $_; # print c +ontents of $_ line by line } close $in or warn "Can't close $file: $!"; __END__ $ perl test.pl Line number: 1 Content of line: ABS0056 Line number: 3 Content of line: ABS0057 Line number: 5 Content of line: ABS0058 Line number: 7 Content of line: ABS0059

    You can read more here perlvar about the special variables e.g. $. that can help you to get the line number. I would suggest also to use chomp in general removes the new line character \n but it does more things than just that. Read the documentation for more information.

    I would also skip the blank lines on your file since there is no need to process them, use next with a regular expression to detect the blank lines.

    Update: You can also take advantage of the eof and simply pass all the files you want to process through the initialization of your script and you do not need to open and close the files this will be handled by the script for you. Sample of code with the use of Data::Dumper for complex data structures analysis:

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; use feature 'say'; my %hash; # reset line numbering on each input file while (<>) { chomp; next if /^\s*$/; # skip blank lines say "$.\t$_"; $hash{$ARGV}{$.} = $_; } continue { close ARGV if eof; # Not eof()! } print Dumper \%hash; __END__ $ perl test.pl file1.txt file2.txt 1 ABS0056 3 ABS0057 5 ABS0058 7 ABS0059 1 ABS0060 3 ABS0061 5 ABS0062 7 ABS0036 $VAR1 = { 'file2.txt' => { '7' => 'ABS0036', '5' => 'ABS0062', '1' => 'ABS0060', '3' => 'ABS0061' }, 'file1.txt' => { '5' => 'ABS0058', '7' => 'ABS0059', '1' => 'ABS0056', '3' => 'ABS0057' } };

    Update2: Thanks to fellow monk 1nickt I remembered one of my favorite modules that is also able to parse files and do many more things IO::All. Sample of code:

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; use IO::All -utf8; # Turn on utf8 for all io my @lines = io('file.txt')->chomp->slurp; # Chomp as you slurp print Dumper \@lines; __END__ $ perl test.pl $VAR1 = [ 'line 1', 'line 2', 'line 3', 'line 4' ];

    Hope this helps, BR.

    Seeking for Perl wisdom...on the process of learning...not there...yet!
Re: iterative foreach loop
by zarath (Beadle) on Nov 15, 2017 at 11:09 UTC

    Hello!

    For the task you are describing I would use the following code:

    use strict; use warnings; use autodie; my $filename = 'Text2.txt'; my $count = 0; open my $file,'<',$filename; while (my $line = <$file>) { ++$count; # keep track of the number of lines printf "Line $count: $line"; } close $file; exit 0;

    Note: when I need to open files for any reason, I tend to use autodie; so I can forget to add or die $!; to each open.

    This code literally just opens your .txt-file and prints the following: "Line " number of the line ": " content of the line. It does not do much more.

    But you did mention you would like to store the lines into an array. For later use perhaps?

    In this case it would become this code:

    use strict; use warnings; use autodie; my $filename = 'Text2.txt'; my $count = 0; my @lines; # declare the array to be used for storing open my $file,'<',$filename; while (my $line = <$file>) { ++$count; # keep track of the number of lines push (@lines,'Line ',$count,': ',$line); # fill the initially empt +y array with the needed data } close $file; # do not need this anymore for my $newline (@lines) { printf $newline; # print the contents of the filled array } exit 0;

    The result of both codes is the same, but in the second version all lines (with linecount) are stored inside the array @lines so you can easily use it for whatever you want after the while-block is closed without needing to read from $file again. This would be more difficult in the first version I think.

    You can of course format the lines of your array however you like it by editing the push: push (@array,'fill','this','however','you','want');

    Hope this is helpful.

      for my $newline (@lines) { printf $newline; # print the contents of the filled array }

      This seems confusingly verbose to me. Why not simply

      print @lines;

      There's no need for printf, for an explicit loop or for a lexical scalar. TIMTOWTDI, but there is clarity in simplicity.

        Good points, thanks for that!

        I think I picked up some bad habits by learning Perl mainly from some old scripts I've come across at work.

        Starting to think the guy who wrote them shouldn't have...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1203349]
Approved by marto
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-04-25 13:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found