Click to See Complete Forum and Search --> : Reading data
SniperX
04-24-2003, 06:23 AM
Hi everybody,
Does any one know how to read a single line of data from a text file?
e.g. I have a text file called Test.txt, and i want to read the data at line 5(five), is this possible if so how?
Regards
MW
Charles
04-24-2003, 06:47 AM
my @text = <>;
my $line = $text[4];
or
my $line;
$line = <> for (my $i = 0; $i < 5; $i++);
Lines in a text file are of no fixed length. You will have to step through the file one way or another and count line feeds.
SniperX
04-24-2003, 06:54 AM
Maybe you could help me - im kinda new to this...
I dont understand this bit -
my @text = < >; (what is the < >)
and the for loop thing i dont get,
could you please give me a short code listing as an example?
It would be appreciated.
Regards MW
Scriptage
04-24-2003, 08:40 AM
#!/usr/bin/perl -w
use strict;
my $i = 0; # Counter variable
my $line; # Variable to contain line 5
my $file = "test.txt"; # The file to be read
open(FILE, "$file") || die "Cannot open $file: $!"; # Open the file
COUNTER: while(<FILE>){ # Loop through the file
last COUNTER if($i == 5); # Until line 5 is reached
$line = $_; # Stores the current line into $line
$i++; # Count the lines
}
close(FILE); # Close the file
print "Line 5 contains: $line\n";
Scriptage
04-24-2003, 08:42 AM
#!/usr/bin/perl -w
use strict;
my $i = 0;
my $line;
my $file = "test.txt";
open(FILE, "$file") || die "Cannot open $file: $!";
COUNTER: while(<FILE>){
last COUNTER if($i == 5);
$line = $_;
$i++;
}
close(FILE);
print "Line 5 contains: $line\n";
jeffmott
04-24-2003, 10:28 AM
The counter variable can be eliminated since Perl already has a predefined variable for the line number.my $line;
open FH, 'test.txt' or die $!;
while (<FH>) {
next unless $. == 5;
$line = $_;
last;
}
close FH;
Scriptage
04-25-2003, 06:58 PM
That's all well and good jeff...good example...but....
I wrote a program that would show him/her exactly what was going on...which is what he/she needs as he/she is learning...
regards
Scriptage
04-25-2003, 07:00 PM
I'm not trying to er....P**s you off Jeff (I know that you are about 100 * better than me at Perl!!!)
Regards