Compact way of getting file checksum in Perl

前端 未结 3 512
清酒与你
清酒与你 2021-01-12 14:47

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

3条回答
  •  無奈伤痛
    2021-01-12 15:15

    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.

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

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

提交回复
热议问题