Return multiple values from a function in hash

旧城冷巷雨未停 提交于 2019-12-25 18:18:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!