The problem is that you're reading the $foo handle before
printing. This has the effect of zapping the first line.
Here's how it goes:
while (<$foo>) # Read in a line to $_
{
print <$foo>; # Print the rest of the file
}
In this case, the first line you read is not actually used.
Instead of your suggestion of while(1), try this:
while (<$foo>) # Read in a line to $_
{
print; # Print $_
}
Or, in a more terse fashion:
print while (<$foo>); # Read in lines and print them
Or, even the approach you seem to have hit on by accident:
print <$foo>; # Print all lines from the file
Those are all simple ways of doing what you are looking for.
If you're using a book for this, I'm curious as to
the name of it, because that is some pretty bizarre Perl.
If, however, this is your own code,
then it is good that you are willing to explore. I am
just worried that this came from a book which advocates
that kind of programming.
What has me mystified in particular is the mixing of
IO::Handle methods and the traditional reading techniques.
Usually you're using
IO::Handle for a reason, but in this
case it seems you're just making your life difficult. Here's
the program written two ways:
# -- IO Implementation --------------------------------
use IO::File;
my $file = 'foo.txt';
my $handle = new IO::File ($file)
|| die "Could not open $file\n";
print $handle->getlines();
$handle->close();
# -- Traditional --------------------------------------
my $file = 'foo.txt';
open (FILE, $file) || die "Could not open $file\n";
print <FILE>;
close (FILE);
The
IO::Handle methods may have more appeal for Java
people who want everything OO. Others find the traditional
method more appealing. Both do the job, so the choice is
yours.
However, try and keep your approach "pure". In some cases,
mixing different types of calls can cause subtle errors,
often when two approaches are mostly, but not entirely
equivalent.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.