vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to fetch a url from artifactory using File::Fetch module. I have only this module install on the server, I can't install other modules. Below is the part of the code.

my $jar='xxxxxx.jar'; my $url = "http://ip_address:port/artifactory/api/search/artifact?name +=".$jar."&repos=xxxxx-3rdparty-libs-local,Central_Maven_repository-ca +che,Jcenter,Jcenter-cache,FuseSource,MavenRedHat,ApacheArchive,Centra +l_Maven_2_repository-cache,xxxxx-3rdparty-libs-common,Central_Maven_2 +_repository,Central_Maven_repository,Jcenter and Gradle-Remote"; my $response; my $ff = File::Fetch->new(uri => $url); $ff->fetch( to => \$response) or die $ff->error; print Dumper $response;

I am fetching the url into a scalar variable and it prints as,

$VAR1 = '{ "results" : [ { "uri" : "http://ipaddress:port/artifactory/api/storage/Central_Mav +en_2_repository-cache/org/xxxxx.jar" }, { "uri" : "http://ipaddress:port/artifactory/api/storage/xxxxx-3rdpa +rty-libs-local/org/xxxxx.jar" } ] }';

Initially I thought it is a hash ref, and tried to access as,

print $response->{'results'};

But got blow error

Can't use string ("{ "results" : [ { "uri" : "...) as a SCALAR ref while "strict refs" in use at artifa +ctory_url.pl line 39.

I need the first uri available in the $response variable? How to convert this string to hash ref ?

For now I used below code to parse the first uri from the response, I hope there should be a better way to get the first uri from the response.

if ($response =~/"uri" : "(.*?)"/){ print($1."\n"); }else{ print("Fetch failed\n"); }

All is well. I learn by answering your questions...

Replies are listed 'Best First'.
Re: File::Fetch fetch to scalar
by choroba (Cardinal) on Jul 02, 2021 at 18:38 UTC
    It's not a hash ref, it's a JSON. JSON::PP is core, so it should be installed:
    use JSON::PP; my $uri = decode_json($response)->{results}[0]{uri};

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Hi choroba

      Thanks, It works. But how do I know its json content? The File::Fetch document does not explain the scalar content is json.


      All is well. I learn by answering your questions...

        You could start by checking the MIME type:

        #!/usr/bin/env perl use strict; use warnings; use LWP::UserAgent; my $ua = LWP::UserAgent->new; my @urls = ( 'https://jsonplaceholder.typicode.com/todos/1', 'https://www.perl.org/' ); for my $url (@urls) { my $res = $ua->get ($url); print index($res->header('Content-Type'), 'application/json') > -1 + ? "$url is JSON\n" : "$url is not JSON\n"; }

        🦛

        File::Fetch just downloades content, it doesn't create.