开发者

How can I read input from a text file in Perl?

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 t开发者_高级运维o do this simple task of printing every line of text file. So how to do it? I am new to Perl, thus the confusion .


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.


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 $!;


# 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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜