-1

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
nims
  • 103
  • 1
  • 8
  • If it works, don't fix it! I would leave the functional code alone and append a function to translate scalar to hash. I know that is not an answer, but it keeps your working code intact. –  Apr 13 '16 at 02:02
  • 1
    @Sparky256 if i want to return multiple values , i don't think its a good idea to use a scalar. I guess hash ref would be a good option. – nims Apr 13 '16 at 02:06
  • Is this your real code? What is `$self`? And especially, what is `$out`? Your loop `foreach my $line ( $out )` will execute exactly once, so there is no need for the loop. Is that what you expect? – Borodin Apr 13 '16 at 02:07
  • Exact duplicate of http://stackoverflow.com/q/36138778/5830574 – PerlDuck Apr 13 '16 at 09:54

1 Answers1

3

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})");
Borodin
  • 126,100
  • 9
  • 70
  • 144
  • i have used some internal libraries created at my work place. {sshObj}->exec(), exec() is a function,that is part of our internal framework of our organization. Your answer is perfect and works as expected. – nims Apr 13 '16 at 04:13