Does this algorithm guarantee uniform probability for all lines? Seems like the original ordering of the lines is a factor.
https://en.wikipedia.org/wiki/Reservoir_sampling
IMO it's a lot clearer if it's not in Perl ...
The pseudocode in Wikipedia also avoids division.
What isn’t?
It didn't sound plausible to me (because I misunderstood what the algorithm was; yay perl), hence quickly testing it, but it seems to work, and after appreciating what the algorithm actually is (see sibling replies), it not only works but it _should_ work. (There is a CS versus engineering joke in here, somewhere.)
It's a special case of reservoir sampling.