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.


In reply to Re: iterative foreach loop by zarath
in thread iterative foreach loop by hchana

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.