Perl 编程/文件句柄
外观
< Perl 编程
此方法将整个文件读入一个数组。 它将根据特殊变量进行分割$/
# Create a read-only file handle for foo.txt
open (my $fh, '<', 'foo.txt');
# Read the lines into the array @lines
my @lines=<$fh>;
# Print out the whole array of lines
print @lines;
此方法将逐行读取文件。 这将减少内存使用量,但程序必须在每次迭代时轮询输入流。
# Create a read-only file handle for foo.txt
open (my $fh, '<', 'foo.txt');
# Iterate over each line, saving the line to the scalar variable $line
while (my $line = <$fh>) {
# Print out the current line from foo.txt
print $line;
}
使用IO::File,您可以获得更现代的 Perl 文件句柄的面向对象接口。
# Include IO::File that will give you the interface
use IO::File;
# Create a read-only file handle for foo.txt
my $fh = IO::File->new('foo.txt', 'r');
# Iterate over each line, saving the line to the scalar variable $line
while (my $line = $fh->getline) {
# Print out the current line from foo.txt
print $line;
}
# Include IO::File that will give you the interface
use IO::File;
# Create a read-only file handle for foo.txt
my $fh = IO::File->new('foo.txt', 'r');
my @lines = $fh->getlines;
# Print out the current line from foo.txt
print @lines;