问题
I have created a function which essentially logs into a router,executes a command, parses the command output and prints the Peer status
and Peer ip
Function returns the values as expected. In addition to status and peer ip if i want to return 3 more values say for eg: $session_id, $session_state and $time. How do I do that with hash ? I want the function to return all the five values in a Hash.
sub session_status {
my ($self,$interface_name) = @_;
my $status = 0;
my $peer_ip = 0;
#command to chek the status
my $cmd = 'show crypto session interface ' . $interface_name;
$self->_login();
my $tunnel_status = $self->exec($cmd);
#Regex to match the 'tunnel status' and 'peer ip' string in the cmd output
foreach my $line ( $tunnel_status ) {
if ( $line =~ m/Session\s+status:\s+(.*)/ ) {
$status = $1;
}
if ( $line =~ m/Peer:\s+(\d+.\d+.\d+.\d+)/ ) {
$peer_ip = $1;
}
}
return ($status,$peer_ip);
}
Function call:
my ($tunnel_status, $peer_ip) = $sshobject->session_status("Tunnel1");
print "TUNNEL STATUS : $tunnel_status\n";
print "PEER IP : $peer_ip\n";
output :
TUNNEL STATUS : DOWN
PEER IP : 100.81.1.42
回答1:
Try this:
return { 'status' => $status, 'peer_ip' => $peer_ip,
'session_id' => $session_id, 'session_state' => $session_state,
'time' => $time };
And then you can do this:
my $stuff = $sshobject->session_status("Tunnel1");
print "TUNNEL STATUS : $stuff->{'status'}\n";
print "PEER IP : $stuff->{'peer_ip'}\n";
# etc
来源:https://stackoverflow.com/questions/36138778/return-multiple-values-from-a-function-in-hash