在 Perl 中将文件放入字符串的最佳方法是什么? [英] What is the best way to slurp a file into a string in Perl?

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

问题描述

是的,有不止一种方法可以做到但必须有一个规范的或最高效或最简洁的方式.我会添加我知道的答案,看看有什么会渗透到顶部.

Yes, There's More Than One Way To Do It but there must be a canonical or most efficient or most concise way. I'll add answers I know of and see what percolates to the top.

明确地说,问题是如何最好地将文件内容读入字符串.每个答案一个解决方案.

To be clear, the question is how best to read the contents of a file into a string. One solution per answer.

推荐答案

这个怎么样:

use File::Slurp;
my $text = read_file($filename);

预计到达时间:注意 Bug #83126 for File-Slurp:带有编码的安全漏洞(UTF-8).我现在推荐使用 File::Slurper(免责声明:我写的),也是因为它有更好的编码默认设置:

ETA: note Bug #83126 for File-Slurp: Security hole with encoding(UTF-8). I now recommend using File::Slurper (disclaimer: I wrote it), also because it has better defaults around encodings:

use File::Slurper 'read_text';
my $text = read_text($filename);

Path::Tiny:

use Path::Tiny;
path($filename)->slurp_utf8;

这篇关于在 Perl 中将文件放入字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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