Search code examples
perloopparametersperl-modulesubroutine

Send Parameter to Multiple Subroutines in Perl Module


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?


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, ...);