On 7/19/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
On Jul 18, 6:16 am, [EMAIL PROTECTED] (Ayesha) wrote:
> Hi all
>
> I got started on Perl only today!
> I have a text file in which I need to read a line and the line after
> that. Like
>
> line1 and line2
> line2 and line3
> line3 and line4
>
> when I use while($line1 = <MYFILE>){
> $line = <MYFILE>;
> }
>
> I get output
> line1 and line2
> line3 and line4 ..etc. I guess everytime I read a line, it increases
> the counter and reads the next line. I tried playing with the $.
> variable, but it did not help.
>
> Any suggestions here will be very helpful
>
> thanks
> Ayesha
Hello Ayesha,
This code will do the work.It works for me at
least..
#!/usr/bin/perl -w
$file="mini.txt";
open(FH,"<$file") || die "unable to open file";
while ($line=<FH>)
{
print"$line";
}
close(FH);
This code has three problems and several style issues*:
1. it does not use strict
2. while ($line = <FH>) is not safe; use while (defined (my $line =
<FH>)) instead
3. it does not do what the original poster wanted
The original post was asking how to read two lines without consuming
the second line (so it could be read again the next time through the
loop). There are a couple of ways to achieve this effect: use tell
and seek to manage the file pointer and keep a copy of the last line
read.
* The style issues are
1. you are using the two argument version of open, this is bad because
a file named with a mode operator as the first character will cause
problems. Always use the three argument version open
FILEHANDLE,MODE,EXPR
2. you are using old style filehandles, these are global entities that
can cause an number of headaches, use the new lexical versions instead
3. your error message neglects to tell the user why the open failed
(and which file was trying to opened.
4. In print "$line"; the quotes are useless
Here is the code cleaned up (using your indent style, even though it
is not the One True Bracing Style)
#!/usr/bin/perl
use warnings;
use strict;
my $file = "mini.txt";
open my $fh, "<", $file
or die "unable to open $file:$!";
while (defined (my $line = <$fh>))
{
print $line;
}
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/