Search code examples
perllwp

Perl & LWP: getstore() will only save a file if I don't specify a directory


I'm probably missing something simple but I have got getstore() running perfectly to save a ".png" file to my Windows PC as follows:

getstore("$url","$filename");

That works a treat and downloads the file perfectly to the directory containing the Perl script. However if I try saving it to a subfolder of "newdir" nothing downloads:

getstore("$url","newdir\\$filename");

Any idea where I'm going wrong here or how I could debug? I tried printing the directory and it looks good:

print "newdir\\$filename";

However there's nothing in "newdir" once the script runs. Thanks in advance.


Solution

  • The file is opened using open(my $fh, ">", $arg), where $arg contains the value you pass. As such, it will most definitely accept relative paths.

    >dir /b newdir
    
    >perl -MLWP::Simple=getstore -e"getstore('http://stackoverflow.com/', 'newdir\\so.html')"
    
    >dir /b newdir
    so.html
    

    Maybe $filename isn't valid (e.g. ends with a newline). Maybe the current directory isn't what you think it is (it can be a directory other than the one containing the script). Maybe the user as which the script is executing doesn't have access to the directory. You should be able to get more information using:

    use LWP::UserAgent qw( );
    my $ua = LWP::UserAgent->new();
    my $request = HTTP::Request->new(GET => $url);
    my $response = $ua->request($request, "newdir\\$filename");
    die($response->status_line)
       if !$response->is_success;