Question

I'm trying to check to see if a disk or disk image is 'empty'. I'm going to assume that this is true if the first 1mb and last 1mb are zeroes. I started by trying to recreate hexdump but it seems a little convuluded at this point.

Here's roughly my code:

open DISK, $disk or die $!;
for( 1 .. 1024 ) {
    $buffer = undef;
    sysread(DISK, $buffer, 1024, 0) or last;
    for ( split //, $buffer ) {
        if( ord($_) =~ /[^0]/ ) {
            $flag++;
        }
    }
}

Is there a better way to do this?

Was it helpful?

Solution

Check directly if the byte string $buffer contains anything other than \0 bytes.

if ($buffer =~ /[^\0]/) {
    $flag++;
}

OTHER TIPS

Why use a RE there? Can just do ord($_) > 0, no? Also, if all you care is flagging once you find a non-zero byte, just abort after you find it, and don't bother scanning the rest of the disk:

open DISK, $disk or die $!;
for( 1 .. 1024 ) {
    my $buffer = undef;
    sysread(DISK, $buffer, 1024, 0) or last;
    for ( split //, $buffer ) {
        if( ord($_) > 0 ) {
            die "Non-zero byte found";
        }
    }
}

Why loop yourself? You can just use List::Util's first function. It also short circuits.

use List::Util qw(first);
$flag++ if first { ord($_) > 0 } split(//, $buffer);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top