跳转到内容

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;
前一页: 高级输出 索引 下一页: 修饰符
华夏公益教科书