CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Advanced:
Read only one line from text file

 



ragha12
Novice

Sep 22, 2011, 9:45 PM

Post #1 of 4 (3027 views)
Read only one line from text file Can't Post

Hi,
I am using strawberry perl in windows and perl express IDE
I have a text file that contains 10 lines, i have to print only 1 line from that text file......and we have to use only while loop......

this is the code that i have.....
this code is printing all the lines....

#!/usr/bin/perl
open (MYFILE, 'dmb.txt');
while (<MYFILE>) {
chomp;
print "$_";
}
close (MYFILE);


Thank you... Smile


rovf
Veteran

Sep 23, 2011, 12:06 AM

Post #2 of 4 (3016 views)
Re: [ragha12] Read only one line from text file [In reply to] Can't Post

And, in addition, don't post a beginner's question to an advanced forum.


Jukari
Novice

Oct 28, 2011, 6:41 AM

Post #3 of 4 (2803 views)
Re: [rovf] Read only one line from text file [In reply to] Can't Post

open(FILE,"File.txt") || die("Cannot Open File");
while (<FILE>)
{
$line = @_;
chomp($line);
$count++;
if($count eq 1)
{
$one_line = $line;
}
}
close(FILE);

This is my solution, I'm sure there are better variants out there.. But yes this is a beginner question.


rovf
Veteran

Oct 28, 2011, 7:09 AM

Post #4 of 4 (2798 views)
Re: [ragha12] Read only one line from text file [In reply to] Can't Post

Strangly, my first response, giving a solution to your question, did not show up in the forum :-(

Well, Jukari already gave an answer, though I personally consider his one as overly complicated. This would be a simpler version:


Code
use strict; use warnings FATAL => qw(all); 
open(my $file, 'dmb.txt') || die "Damn it! $!\n";
print(q().(<$file> // qq());
close $file;
while(0) {
say "This is only because the requirement says to use a while loop";
}


As you can see, this solution requires less variables than the one provided by Jukari, plus it has error handling.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives