Perl: Read web text file and “open” it

2019-05-03 08:19发布

问题:

I'm trying to create a script that will read text files and then analyse them, regardless of whether the text file is online or offline.

The offline part is done, using

open(FILENAME, "anyfilename.txt")
analyze_file();

sub analyze_file {
   while (<FILENAME>) {analyze analyze}
}

Now for the online part, is there anyway to read a text file on a website and then "open" it?

What I hope to achieve is this:

if ($offline) {
   open(FILENAME, "anyfilename.txt")
}
elsif ($online) {
   ##somehow open the http web text so that I can do a while (<FILENAME>) later
}

analyze_file();

sub analyze_file {
   while (<FILENAME>) {analyze analyze}
}

There's the "get('http://weblink.com/textfile.txt;)" but it creates a string. I can't do a while () with that string.

Does anyone know how this can be done?

回答1:

It's simple, just use the open FILEHANDLE,MODE,REFERENCE style of open.

use LWP::Simple;
if ($offline) {
   open( FILENAME, '<', "anyfilename.txt" )
}
elsif ($online) {
   my $text = get 'http://example.com';
   open( FILENAME, '<', \$text );
}