After this , I need to get exactly n lines randomly from a file (or stdin ). It will look like a head or tail , except that I want some of them to be in the middle.
Now, with the exception of the loop through the file with the solutions to the related question, what's the best way to get exactly n lines in one go?
For reference, I tried this:
#!/usr/bin/perl -w use strict; my $ratio = shift; print $ratio, "\n"; while () { print if ((int rand $ratio) == 1); }
where $ratio is the rough percentage of the rows I want. For example, if I want 1 out of 10 lines:
random_select 10 a.list
However, this does not give me the exact amount:
aaa> foreach i ( 0 1 2 3 4 5 6 7 8 9 ) foreach? random_select 10 a.list | wc -l foreach? end 4739 4865 4739 4889 4934 4809 4712 4842 4814 4817
Another thought that I had was to split the input file and then select n randomly from the array, but this is a problem if I have a really large file.
Any ideas?
Edit: This is an exact duplicate of this question.
perl random-sample
Nathan fellman
source share