heezy has asked for the wisdom of the Perl Monks concerning the following question:

I want to use the Unix command ckSum to generate a simple checksum for a file and store this for use in my program.

The system command returns success/failure {wait()} of whatever it executes but I want to get at the value...

$chkSum = system("cksum $file");

...the above returns either 0 or 256 depending on success/failure.

I think this is quite a basic thing to achieve but I'm lost.

Thanks

Mark

Replies are listed 'Best First'.
Re: Capturing Results Of A System Command
by Chmrr (Vicar) on Sep 23, 2002 at 22:46 UTC

    This is a FAQ. You want to use backticks, like so:

    $chksum = `cksum $file`;

    ..the standard caveats about being careful about special characters in $file apply.

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

Re: Capturing Results Of A System Command (use a digest function)
by grinder (Bishop) on Sep 24, 2002 at 07:49 UTC
    If you are interested in generating checksums for files, the recommended practice these days is to use a digest function, and one that springs to mind is Digest::MD5. As this is a Perl module, it also means that you can calculate a checksum without relying on an external program. Here is a sample script to get you up and running:

    use strict; use Digest::MD5 qw/md5_base64/; my $file = shift or die "No file specified on command-line.\n"; open IN, $file or die "Cannot open $file for input: $!\n"; my $digest = md5_base64(<IN>); close IN; print "Digest of $file is $digest\n";

    Digest::MD5 has much stronger properties for guaranteeing that a given file has not been modified, and that two different files are indeed different, than the standard Unix checksum program.


    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'