perlhttplwpremote-host

Perl: test if remote file exists http


Hello Everyone!

I need to test if a remote file on a http server exists without downloading it. I looked into various command line programs like wget, curl, axel, but could not find a test-only flag.

I am working in an production environment and only have a limitations on modules I can work with. Looking around, the LWP::Simple->head() function seems suitable, but returns undef when trying it:

#!/usr/bin/perl -w
use strict;
use LWP::Simple;

  my $url = 
'http://hgdownload.cse.ucsc.edu/goldenPath/hg18/encodeDCC/wgEncodeUwChIPSeq/wgEncodeUwChIPSeqAlignmentsBjInput.tagAlign.gz';

 my $head = LWP::Simple->head($url);
 #my $head = head($url);

 print "$head\n";

Any pointers greatly appreciated!

Thanks, Thomas


Solution

  • head is an exported function, not a class method. You are invoking it wrong.

    use LWP::Simple qw(head);
    
    my $url = …
    if (head($url)) {
        # sucess
    } else {
        # no success
    }
    
    # alternatively skip the import, supply fully qualified function name:
    # use LWP::Simple qw();
    # if (LWP::Simple::head($url)) …