I wanted to do a POST request to jira and jfrog. while I try to get the values of the hash within the loop am not able to get the value the second time. I try to read the variable(API token instead of password) from env, if not set it will pass the username and password.
my %urls = (
'jira' => {
'url' => 'https://jira.com:123/rest/api/2/issue/',
'token' => 'JIRA_TOKEN'
},
'jfrog' => {
'url' => 'https://jfrog.com/artifactory/api/storage/path/to/artifacts',
'token' => 'JFROG_TOKEN'
}
);
my $jira_ua = Mojo::UserAgent->new();
for my $outer_elem ( keys %urls ) {
for my $inner_elem ( keys %{$urls{$outer_elem}} ) {
# print $inner_elem;
if ( !$ENV{$urls{$outer_elem}{'token'}} ) {
print "Enter username : \n";
my $username = <STDIN>;
chomp($username);
my $passwd = read_password("Enter Password: ");
$url = Mojo::URL->new($urls{$outer_elem}->{'url'})
->userinfo($username.':'.$passwd);
}
else {
if ( $inner_elem eq "jira" ) {
$tx->req->headers->authorization (
"Bearer $ENV{$urls{$outer_elem}->{'token'}}"
);
$url = Mojo::URL->new($urls{$outer_elem}->{'url'})
}
}
print $outer_elem . "\n";
print "logging in to $urls{$outer_elem}->{'url'}\n";
$tx = my $ua->get($url); # <--- line 170
my $res = $tx->res->code;
print $res;
last;
}
}
I get below output
D:\scripts>perl emtf.pl
jira
Can't call method "get" on an undefined value at emtf.pl line 170.
The error you're getting is:
Can't call method "get" on an undefined value
And the line of code that generates the error is:
$tx = my $ua->get($urls{$outer_elem}->{'url'});
The error means that $ua
contains undef
when you try to call the get()
method on it. That's because you create a new variable called $ua
on this line of code - that's what my
does. And because you don't assign a value to this new variable, it will contain undef
.
I'm not sure why the my
is there. And I'm not sure I really understand how your code is supposed to work. There's another variable called $ua
that is defined but not used in the anonymous subroutine that's defined a few lines above (my( $ua, $tx ) = @_;
) but that variable doesn't exist outside that subroutine.
Did you, perhaps mean the line to use $jira_ua
instead:
$tx = $jira_ua->get($urls{$outer_elem}->{'url'});