I want to know if it is possible to return a object handle from a subroutine in a Perl program.
I will use a specific example from a program that uses MAIL::IMAPClient
Create client object handle
my $client = Mail::IMAPClient->new(
Socket => $socket,
User => $user,
Password => $pass,
)
or die "new(): $@";
I would like to create this object handle from a sub routine instead
my $client = &create_client_object;
sub create_client_object {
my $client = Mail::IMAPClient->new(
Socket => $socket,
User => $user,
Password => $pass,
)
or die "new(): $@";
return $client;
}
If possible, what is the proper way to do this?
Yes, that works perfectly. Besides @Miller's comment, I'd recommend you to also pass the $socket
, $user
and $pass
as parameters to your function instead of using them from context:
my $client = create_client_object($socket, $user, $pass);
sub create_client_object {
my ($socket, $user, $pass) = @_;
my $client = Mail::IMAPClient->new(
Socket => $socket,
User => $user,
Password => $pass,
)
or die "new(): $@";
return $client;
}