reading input from a file

hello...
i have recently started learning perl.....and having issues when i try to read input from another file. the details of a script that i tried to run are as follows:

i made a text file by the name "text.txt" and the contents were
Sidra|38|BE
Hira|48|BE
Shagufta|50|BE

Then i wrote the following script

open(DAT, "text.txt");
$data_file=" text.txt ";
open(DAT, $data_file);
@raw_data=;
close(DAT);
foreach $student (@raw_data)
{
chomp($student);
($name,$roll_no,$class)=split(/\|/,$student);
print "The student $name bearing roll number $roll_no is in class $class";
print "
\n";
}


the script produces no output and displays a message saying
"readline () closed filehandle at line "
I tried the same with another file by the name "text.dat" holding the same data but it did not work either. Please help me out resolving this issue.
Thankyou...

5 Comments

You should always (yes, always) check the return value of open(), like this:


open(DAT,"myfile.txt") or die $!;

Also, opening DAT twice can't do any good. Also there are spaces around the filename "text.txt". Also I don't see "use strict;" or "use warnings;", which can teach you a lot about how to write good Perl.

#!/usr/bin/perl

use strict;
use warnings;

open(DAT, "text.txt");
my @raw_data= ;
close(DAT);

for my $student (@raw_data)
{
chomp($student);
my ($name, $roll_no, $class) = split(/\|/,$student);
print "The student $name bearing roll number $roll_no is in class $class\n";
}

I think fixes your version. But learning the good modules on cpan is a great idea

http://search.cpan.org/perldoc?File::Slurp

and more generally

http://maddingue.free.fr/conferences/fpw-2009/best-of-cpan/

or for the google translated version

http://translate.google.com/translate?js=y&prev=_t&hl=en&ie=UTF-8&layout=1&eotf=1&u=http%3A%2F%2Fmaddingue.free.fr%2Fconferences%2Ffpw-2009%2Fbest-of-cpan%2F&sl=fr&tl=en

Which can get you to:

#!/usr/bin/perl

use strict;
use warnings;
use File::Slurp qw;

for my $student (slurp 'text.txt')
{
chomp $student;
my ($name, $roll_no, $class) = split(/\|/,$student);
print "The student $name bearing roll number $roll_no is in class $class\n";
}

"Learning Perl" would also be a good read http://oreilly.com/catalog/9780596520113/

This code does the same thing as yours.

use strict;
use warnings;

my $filename = 'test.txt';
open my $in, '<', $filename
or die "Can't open $filename: $!";

while (<$in>) {
chomp;
my ($name, $roll_no, $class) = split /\|/;
print "The student $name bearing roll number $roll_no is in class $class\n";
}

As an aside, this is a weblog site, not a Perl help forum. If you are looking for help, you are more likely to find more of it faster by posting your questions on http://perlmonks.org/.

Leave a comment

About Hir@

user-pic I blog about Perl.