加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

有没有更有效的方法在Perl中生成随机文件?

发布时间:2020-12-15 21:43:56 所属栏目:大数据 来源:网络整理
导读:这是我的第一个Perl脚本.曾经: #!/usr/bin/perlif ($#ARGV 1) { die("usage: size_in_bytes file_namen"); }open(FILE,"" . $ARGV[0]) or die "Can't open file for writingn";# you can control the range of characters heremy $minimum = 32;my $range
这是我的第一个Perl脚本.曾经:
#!/usr/bin/perl

if ($#ARGV < 1) { die("usage: <size_in_bytes> <file_name>n"); }

open(FILE,">" . $ARGV[0]) or die "Can't open file for writingn";

# you can control the range of characters here
my $minimum = 32;
my $range = 96;

for ($i=0; $i< $ARGV[1]; $i++) {
    print FILE chr(int(rand($range)) + $minimum);
}

close(FILE);

它的目的是到generate a file in a specified size filled with random characters.

它工作但很慢.写一个10MB的随机文件需要几秒钟.
有没有人有关于如何更快/更好的建议/提示?也可以随意指出常见的新手错误.

解决方法

>每次调用它时,您都可以要求rand为您创建多个值.
>在打印之前收集几个字符.一次打印一个字符效率低下.
for (my $bytes = 0; $bytes < $num_bytes; $bytes += 4) {
    my $rand = int(rand($range ** 4));
    my $string = '';
    for (1..4) {
        $string .= chr($rand % $range + $minimum);
        $rand = int($rand / $range);
    }
    print FILE $string;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读