Question

I'm creating a user module to extract user information and currently I have:

sub new
{
    my $class = shift;
    my ( $id ) = @_;
    my $self = getUserInfo ($id);
    bless $self, $class;
    return $self;
}

sub getUserInfo
{
    ...
}

However, I would like to achieve something to the effect of:

my $self = (getFirstName($id), getLastName($id), getEmpNum($id));

...

sub getFirstName{ return { firstname => $firstname }; }
sub getLastName{ return { lastname => $lastname }; }
sub getEmpNum{ return { empnum => $empnum }; }

How do I go about distributing a parameter to multiple subroutines?

Was it helpful?

Solution

I think your general code architecture has a few problems, but the snippets so far don't offer enough context to suggest an alternative solution – consider posting your complete code on Code Review for a more complete criticism.

Regarding your immediate problem: You could write a function to combine the hash references:

use Carp ();

sub combine_hashrefs {
    my %combined;
    for my $hashref (@_) {
        if (my @conflicts = grep { exists $combined{$_} } keys %$hashref) {
            Carp::confess "The keys [@conflicts] are conflicting";
        }
        @combined{keys %$hashref} = values %$hashref;
    }
    return \%combined;
}

...

my $self = combine_hashrefs($hashref_a, $hashref_b, $hashref_c, ...);

OTHER TIPS

Do I understand correctly that you want to avoid the repetition of $id in the following line?

my $self = (getFirstName($id), getLastName($id), getEmpNum($id));

$self is a scalar, so you should rather use the anonymous array [...]. To specify $id only once, you can use

my $self = [ map $_->($id), \&getFirstName, \&getLastName, \&getEmpNum ];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top