在 Perl 中,如何将整个文件读入字符串? [英] In Perl, how can I read an entire file into a string?

查看:54
本文介绍了在 Perl 中,如何将整个文件读入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 .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' [$!]
";  
$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 perlvarperldoc -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 允许您slurpspew.

In addition, Path::Class::File allows you to slurp and spew.

Path::Tiny 提供了更方便的方法,例如 slurpslurp_rawslurp_utf8 以及他们的 spew 同行.

Path::Tiny gives even more convenience methods such as slurp, slurp_raw, slurp_utf8 as well as their spew counterparts.

这篇关于在 Perl 中,如何将整个文件读入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆