Sfairas
Sfairas

Reputation: 942

How do I download a file using Perl?

I'm running Perl on Windows XP, and I need to download a file from the URL http://marinetraffic2.aegean.gr/ais/getkml.aspx.

How should I do this? I have attempted using WWW::Mechanize, but I can't get my head around it.

This is the code I used:

my $url = 'marinetraffic2.aegean.gr/ais/getkml.aspx';
my $mech = WWW::Mechanize->new;
$mech->get($url);

Upvotes: 33

Views: 67311

Answers (5)

DimiDak
DimiDak

Reputation: 5601

Just in case someone needs an oneliner ;)

perl -e 'use File::Fetch;my $url = "http://192.168.1.10/myFile.sh";my $ff = File::Fetch->new(uri => $url);my $file = $ff->fetch() or die $ff->error;'

Just change the content of $url

Upvotes: 3

Tomasz
Tomasz

Reputation: 5509

use WWW::Mechanize;

my $url = 'marinetraffic2.aegean.gr/ais/getkml.aspx';
my $local_file_name = 'getkml.aspx';

my $mech = WWW::Mechanize->new;

$mech->get( $url, ":content_file" => $local_file_name );

This in fact wraps around the LWP::UserAgent->get.

More details can be found at WWW::Mechanize docs page.

Upvotes: 5

maloo
maloo

Reputation: 380

I used File::Fetch as this is a core Perl module (I didn't need to install any additional packages) and will try a number of different ways to download a file depending on what's installed on the system.

use File::Fetch;
my $url = 'http://www.example.com/file.txt';
my $ff = File::Fetch->new(uri => $url);
my $file = $ff->fetch() or die $ff->error;

Note that this module will in fact try to use LWP first if it is installed...

Upvotes: 22

JB.
JB.

Reputation: 42104

If downloading that file is all you actually do, you'd better go with @davorg's answer.

If this is part of a bigger process, you access the ressource you downloaded as a string using method content on your $mech object.

Upvotes: 4

Dave Cross
Dave Cross

Reputation: 69244

I'd use LWP::Simple for this.

#!/usr/bin/perl

use strict;
use warnings;

use LWP::Simple;

my $url = 'http://marinetraffic2.aegean.gr/ais/getkml.aspx';
my $file = 'data.kml';

getstore($url, $file);

Upvotes: 66

Related Questions