Search code examples
perllwp

Assign LWP command to Perl variable


The network guys at my work are applying upgrades and patches that sometimes cause my LWP to error out with http status 500.

I have about 50 Perl apps with the below line of code. Instead of changing all 50 apps each time security protocols change, I'd like to use a variable. However, I can't seem to hit on the right way to assign the LWP to a variable.

Current code that works:

my $ua = LWP::UserAgent->new(ssl_opts =>{ verify_hostname => 0 });

Want to do this, but keep getting errors:

my $lwp = "LWP::UserAgent->new(ssl_opts =>{ verify_hostname => 0 })";
my $ua = $lwp;

I plan to put the lwp string in a file or a module, but coded the above for illustrative purposes.

Any advice on how to do this is greatly appreciated.

Tried these, but they did not work:

my $ua = <$LWP>;
my $ua =  eval "\$$LWP";
my $ua = ${$LWP}; `

Solution

  • I wouldn't go with any eval based approach. The code you eval is a String, so you won't get syntax highlighting in your editor, you cannot run perl -c to check it, and there is just no point to eval.

    A simpler approach would be to just define a function in a module, e.g., UserAgentMaker.pm that you can use and call:

    package UserAgentMaker;
    
    use strict;
    use warnings;
    use LWP::UserAgent;
    
    sub get_lwp {
        return LWP::UserAgent->new(ssl_opts =>{ verify_hostname => 0 });
    } 
    
    1;
    

    Then use it:

    use strict;
    use warnings;
    use UserAgentMaker;
    
    my $ua = UserAgentMaker::get_lwp();
    # use $ua
    

    You can also extend this and create different get_lwp functions if clients need to create them with different options, like a get_legacy_lwp, get get_tls_1_1_lwp and whatever else you need.

    You may need to pass -I to perl so that Perl finds your module. For example, if both are in the same directory:

    perl -I. example.pl