在Perl中,如何将整个文件读取为字符串? [英] In Perl, how can I read an entire file into a string?
问题描述
我正在尝试将.html文件作为一个大的长字符串打开.这就是我所拥有的:
I'm trying to open an .html file as one big long string. This is what I've got:
open(FILE, 'index.html') or die "Can't read file 'filename' [$!]\n";
$document = <FILE>;
close (FILE);
print $document;
其结果是:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN
但是,我希望结果看起来像这样:
However, I want the result to look like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
这样,我可以更轻松地搜索整个文档.
This way I can search the entire document more easily.
推荐答案
添加:
local $/;
从文件句柄读取之前.请参阅 如何我可以一次读取整个文件吗? 或
before reading from the file handle. See How can I read in an entire file all at once?, or
$ perldoc -q "entire file"
请参见 与文件句柄相关的变量 在perldoc perlvar
和 perldoc -f local
中.
See Variables related to filehandles in perldoc perlvar
and perldoc -f local
.
顺便说一句,如果您可以将脚本放在服务器上,则可以拥有所需的所有模块.请参见 如何保留我的自己的模块/库目录? .
Incidentally, if you can put your script on the server, you can have all the modules you want. See How do I keep my own module/library directory?.
此外, Path :: Class :: File 允许您 slurp 和 Path :: Tiny 提供了更多便捷方法,例如 spew
同行.
Path::Tiny gives even more convenience methods such as slurp
, slurp_raw
, slurp_utf8
as well as their spew
counterparts.
这篇关于在Perl中,如何将整个文件读取为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!