If you need random numbers from a range, I don't know a more efficient way. Your script is tuned to my preferences:
#!/usr/bin/perl use warnings; use strict; die("usage: $0 <size_in_bytes> <file_name>\n") unless @ARGV == 2; my ($num_bytes, $fname) = @ARGV; open(FILE, ">", $fname) or die "Can't open $fname for writing ($!)"; my $minimum = 32; my $range = 96; for (1 .. $num_bytes) { print FILE pack( "c", int(rand($range)) + $minimum); } close(FILE);
I use pack("c") when I really need a binary. chr() can also be great, but IIRC really depends on what character is used to encode your environment (I think ASCII vs. utf8.)
By the way, if you really need a binary file for compatibility with Windows, you can add binmode FILE; after open .
Otherwise, if the range is optional, you can simply dd if=/dev/random of=$filename bs=1 count=$size_of_the_output (or faster on crypto-unsafe /dev/urandom on Linux). But this will be much slower since /dev/random really trying to deliver real random bits - as they appear. And if they are not enough (for example, your platform does not have H / W RNG), then the performance will really suffer - compared to the incredibly fast pseudo random number generator libc (Perl uses internally to implement rand() ).
Dummy00001
source share