将文件压缩成Perl中的字符串的最佳方式是什么? [英] What is the best way to slurp a file into a string in Perl?

查看:139
本文介绍了将文件压缩成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);

ETA:note Bug#83126 for File-Slurp:Security hole with encoding(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天全站免登陆