在Perl中获取文件校验和的紧凑方法 [英] Compact way of getting file checksum in Perl

查看:43
本文介绍了在Perl中获取文件校验和的紧凑方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在Perl中获取文件校验和的方法,而不是通过执行系统命令 cksum 来实现–希望在Perl本身中这样做,因为脚本需要可在UNIX和Windows之间移植。 cksum< FILENAME> | awk’{print $ 1}’在UNIX上有效,但在Windows上显然无效。我已经浏览过 MD5 ,但似乎有必要获取文件句柄,并且通常不需要。似乎是获取数据的非常紧凑的方法(最好是单行)。

I am looking for ways to get file checksums in Perl but not by executing the system command cksum -- would like to do it in Perl itself because the script needs to be portable between UNIX and Windows. cksum <FILENAME> | awk '{ print $1 }' works on UNIX but obviously not in Windows. I have explored MD5 but it seems like getting a file handle is necessary and generally it doesn't seem like a very compact way to get that data (one-liner preferable).

有更好的方法吗?

推荐答案

这是三种不同的方法取决于您可用的模块的方式:

Here are three different ways depending on which modules you have available:

use Digest::MD5 qw(md5_hex);

use File::Slurp;
print md5_hex(read_file("filename")), "\n";

use IO::All;
print md5_hex(io("filename")->all), "\n";

use IO::File;
print md5_hex(do { local $/; IO::File->new("filename")->getline }), "\n";

不是完全一行,而是很接近。

Not completely one-line but pretty close.

Digest :: MD5 替换为所需的任何哈希算法,例如SHA1。

Replace Digest::MD5 with any hash algorithm you want, e.g. SHA1.

IO :: File 是核心,应该可以在任何地方使用,但这是我个人不喜欢的解决方案最多。无论如何,它都可以。

IO::File is in core and should be available everywhere, but that's the solution I personally dislike the most. Anyway, it works.

这篇关于在Perl中获取文件校验和的紧凑方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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