tags:

views:

73

answers:

4

I would like to take input from a text file in Perl. Though lot of info are available over the net, it is still very confusing as to how to do this simple task of printing every line of text file. So how to do it? I am new to Perl, thus the confusion .

+3  A: 

First, open the file:

open my $fh, '<', "filename" or die $!;

Next, use the while loop to read until EOF:

while (<$fh>) {
    # line contents's automatically stored in the $_ variable
}
close $fh or die $!;
eugene y
+4  A: 

eugene has already shown the proper way. Here is a shorter script:

#!/usr/bin/perl
print while <>

or, equivalently,

#!/usr/bin/perl -p

on the command line:

perl -pe0 textfile.txt

You should start learning the language methodically, following a decent book, not through haphazard searches on the web.

You should also make use of the extensive documentation that comes with Perl.

See perldoc perltoc or perldoc.perl.org.

For example, opening files is covered in perlopentut.

Sinan Ünür
That would need to be `perl -p -e0 textfile.txt` or `perl -p /dev/null textfile.txt` or similar to keep either stdin or textfile.txt from being treated as the perl program to run.
ysth
If you don't want to put the filename on the command line, I will often hardcode in quick n dirty scripts: @ARGV="filename.txt"; You can also put the "-p" or a "-n" on the shebang (e.g., #!/usr/bin/perl -p) line.
runrig
+1  A: 
# open the file and associate with a filehandle
open my $file_handle, '<', 'your_filename'
  or die "Can't open your_filename: $!\n";

while (<$file_handle>) {
  # $_ contains each record from the file in turn
}
davorg
A: 

If you already know another language, then Rosetta Code is helpful. It has examples of a variety of problems solved in numerous languages. In this case, you would want the section on File IO. By comparing the example in Perl 5 with the example in another language you already know you can get insight into what is going on.

Chas. Owens