I have written a function that executes a command, parses the output based on the regex, and returns two values, status and ip. Function call returns both the values as expected. Instead of returning a scalar, I want to return hash ref. Can some one tell me how to do return a hash ref for the below function?
sub status {
my ($self,$int) = @_;
my $status = 0;
my $ip = 0;
my $cmd = 'cisco ios command ' . $interface;
my $out = $self->{sshObj}->exec($cmd);
foreach my $line ( $out ) {
if ( $line =~ m/Session\s+status:\s+(.*)/ ) {
$status = $1;
}
if ( $line =~ /(\d+.\d+.\d+.\d+)/ ) {
$ip = $1;
}
}
return ($status,$ip);
}
function call :
my ($status, $ip) =
$self->{'$tunnel_obj'}->status($self->{'outer_t_1'});
INFO ("status : $status");
INFO ("ip : $ip");
Output :
status : UP
ip : 172.10.78.33
Apart from my misgivings that I described in a comment above, I would use the code below
The change is essentially to replace $status
and $ip
with elements of hash %ret
, and then return a reference to that hash
But I must say again that the for
loop will be executed only once, and this code is wrong as it stands. I can correct it only if you say what modules you are dealing with
sub status {
my ( $self, $int ) = @_;
my $out = $self->{sshObj}->exec("cisco ios command $interface");
my %ret;
for ( $out ) {
$ret{status} = $1 if /Session\s+status:\s+(.*\S)/;
$ret{ip} = $1 if /(\d+.\d+.\d+.\d+)/;
}
\%ret;
}
Your function call would be
my $ret = $self->{$tunnel_obj}->status($self->{outer_t_1});
INFO("Status: $ret->{status}");
INFO("IP: $ret->{ip})");