" . $ARGV[0]) or die "Can't open-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:52:12 26 4
gpt4 key购买 nike

这是我的第一个 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 writing\n";

# 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每次调用时为您创造多个值(value)。
  • 打电话前收集几个字符print .一次打印一个字符效率低下。

  • 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;
    }

    关于perl - 有没有更有效的方法在 Perl 中生成随机文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3445223/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com