Firstly, it's always a good idea to check if the likes of open have succeeded e.g
open(file1, "sample.txt") or die("ack - $!");
Or you could always use the Fatal module to do that for you.

Now on the second line you are reading the entire file into memory.

print(<file1>);
This is because you are evaluating the filehandle readline operator in a list context, which (prototypes forbidding) is how all function arguments are evaluated, and in list context the filehandle readline operator will read until an eof has been reached. Now when you go to assign $line1 the filehandle file1 has read to the end of the file so returns nothing. Now if you want to get back to the beginning of the file then you'll need to use seek which sets the filehandle's pointer e.g
seek(file1, 0, 0);
However if you simply want to print a single line from file1 then you'll need to force scalar context which can be done using the scalar function e.g
print scalar(<file1>);
See. open, readline, eof, seek, scalar and the Input and output functions section of perlfunc for more info.
HTH

_________
broquaint


In reply to Re: Reading from a file by broquaint
in thread Reading from a file by itzMe

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.