Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a hash using elements of the same hash

Tags:

perl

Stupid perl question. Say I'm preparing some API calls, and I want to declare the needed variables in a hash for neatness. How do I refer back to the same hash I'm declaring as I'm declaring it?

my %api_hash = (
     'api_endpoint1' => {
             'username' => 'foo',
             'password' => 'bar',
             'api_url'  => 'https://192.168.1.10:9200',
             'headers'  => {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)}
     },
     'api_endpoint2' => {
             'username' => 'bah',
             'password' => 'wizz',
             'api_url'  => 'https://192.168.1.20:9182',
             'headers'  => {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)}
     }
);

Instead of $username and $password in $api_hash{<endpoint name>}{'headers'}, how would I set those to $api_hash{<endpoint name>}{'username'} and $api_hash{<endpoint name>}{'password'} in the same declaration statement?

like image 796
coding_hero Avatar asked May 07 '26 15:05

coding_hero


1 Answers

You can use a function to build the four key-value pairs of from your three inputs.

sub api_endpoint {
    my ($user,$pw,$url) = @_;
    return { username => $user, password => $pw, api_url => $url,
             headers => { Accept => 'application/json', 
                          Authorization => 'Basic ' . encode_base64($user . ':' . $pw)} }
}

my %api_hash = (
    api_endpoint1 => api_endpoint('foo','bar','https://192.168.1.10:9200'),
    api_endpoint2 => api_endpoint('bah','wizz','https://192.168.1.20:9182'),
    ...
);

Or to retain more of the look and feel of a hash declaration, have the function accept as much of the hashref as it can and return the hashref with the fourth argument

sub api_endpoint {
    my ($ep) = @_;
    $ep->{headers} = {
        Accept => 'application/json', 
        Authorization => 'Basic ' 
             . encode_base64($ep->{username} . ':' . $ep->{password}
    };
    return $ep;
}

my %api_hash = (
     'api_endpoint1' => api_endpoint({
             'username' => 'foo',
             'password' => 'bar',
             'api_url'  => 'https://192.168.1.10:9200',
     }),
     'api_endpoint2' => api_endpoint({
             'username' => 'bah',
             'password' => 'wizz',
             'api_url'  => 'https://192.168.1.20:9182',
     })
);
like image 135
mob Avatar answered May 10 '26 08:05

mob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!