In this section of code I need to read from file.txt randomly:

open my $fh, '<', 'file.txt' or die $!;

while ( <$fh> ) { 
next unless /\S/;
my $response = $ua->get( "http://$_.domain.tld/" );

How to read lines from file.txt randomly?


Files are accessed sequentially.

What you can do is read the entire file into an array and select a random entry from that.

  • More specific: TEXT files are read sequentially. – RudiC Sep 20 '18 at 7:15
  • So I should have added "on the system level". Different types of files is an abstraction some programming languages offer, and the read(2) syscall (fairly directly available by the perl function sysread) "only" supports reading a number of bytes (but you can of course seek around as much as you want, and nowadays there's also pread(2)) so anything else is basically always achieved by some kind of caching. – Henrik supports the community Sep 20 '18 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.