1

I have Class A with following constructor:

sub new {
    my ($class, %args) = @_;

    return bless(\%args, $class);
}

I have another class, LWP::UserAgent, which I want to use in my Class A. I could solve the problem by doing this:

ua = LWP::UserAgent->new;

sub new {
    my ($class, %args) = @_;

    return bless(\%args, $class);
}

But in this case I will have 1 object of UserAgent, but I want a unique object for each instance of my Class A.

zdim
  • 64,580
  • 5
  • 52
  • 81
Nazar
  • 45
  • 4

1 Answers1

3

Then you need to construct that object as an attribute

use LWP::UserAgent;

sub new {
    my ($class, %args) = @_;

    return bless { %args, lwp => LWP::UserAgent->new }, $class;
}

and now every object of class A will have for attribute lwp its own LWP::UserAgent object.

I would of course expect that in reality this is written out nicely with all requisite error checking.


And I guess better call the attribute ua (instead of lwp above), for User-Agent.

zdim
  • 64,580
  • 5
  • 52
  • 81
  • Could you please tell me following: Is "{ %args, lwp => LWP::UserAGent->new }" the same as following code? ```$args{lwp} = LWP::UserAgent->new; return bless(\%args, $class); ``` – Nazar Apr 23 '19 at 04:27
  • @Nazar Yes, and doing `\%args` is a (bit) more efficient than copying it with `{ %args }`. However, this is done _once_ per object's lifetime. Just how many objects does that code create? I'd write it out nicely -- i think you really have to, in order to check the user input (the `%args`). – zdim Apr 23 '19 at 04:33
  • I don't think I will create more than 2-3 objects. But just to be flexible I decided to move this logic out of class to instance. I use Params::ValidationCompiler to validate user* input but not lwp object. Since lwp object is internal and I don't want user to modify it on constructor step. – Nazar Apr 23 '19 at 04:41
  • @Nazar Ah, OK, you have (even proper!) validation in place. (I don't know the module but I can expect that it's good.) – zdim Apr 23 '19 at 04:51
  • Yep :) Thanks again for your help! – Nazar Apr 23 '19 at 04:56