1

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?

4

3 回答 3

6

直接检查字节字符串是否$buffer包含字节以外的任何内容\0

if ($buffer =~ /[^\0]/) {
    $flag++;
}
于 2012-03-02T22:07:37.617 回答
1

为什么要在那里使用 RE?可以做ord($_) > 0,不是吗?此外,如果您只关心在找到非零字节后进行标记,则在找到它后中止,并且不要费心扫描磁盘的其余部分:

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";
        }
    }
}
于 2012-03-02T22:06:30.107 回答
1

为什么要自己循环?你可以只使用 List::Util 的first函数。它也会短路。

use List::Util qw(first);
$flag++ if first { ord($_) > 0 } split(//, $buffer);
于 2012-03-02T22:44:34.903 回答