I have written a perl function that executes a command and parses the command output. The command will provide the output mentioned below. In the function call i pass a number between 1 to 5 as arguments . '1' correspond to lan, 2 corresponds to wan, '3' corresponds to name and so on. ( see the output below) . for example if 1 is passed as an argument in the function call the expected output is '0' ( 1 = lan and value of lan = 0 ) . When i execute the script im not getting the expected output. null is returned.Any suggestions?
command output 1 :
[
{
"lan" : 0, #1
"wan" : 0, #2
"name" : "XYZ", #3
"packets" : 0, #4
"bytes" : 0 #5
}
]
Function call
$self->{'stats_obj'} = Statistics->new( ip => "ip addr")
my $result = $self->{'stats_obj'}->statistics_get('1');
INFO('statistics:' . $result );
Function:
sub statistics_get{
my ($self, $option)= @_;
my $result = $self->_get_hyd_tc();
return $result->{$option};
}
sub _get_hyd_tc {
my ($self) = @_;
my $opt;
my %result;
my $line;
my $cmd = 'cmd goes here';
$self->execute($cmd);
my $count =0;
foreach my $line ( $self->output() ) {
chomp $line;
if ( $line =~ /(Requested table doesn't.*)/i ){
ERROR('table doesnt exist' . $line)
}
if ($line =~ /(.*)/) {
$opt = $1;
$count = 0;
}
elsif ( $line =~ /(.*)/) {
my $key = $1;
my $value = $2;
$result{$opt}{++$count} = $value;
}
}
return \%result;
}
elsifin_get_hyd_tcwill never be entered. Why are you using the same condition in both theifand theelsif? And why are you using a condition that will match any string?.*means match zero or more characters.JSON-format and your problem can be solved without any parsing on your part as the JSON module comes with perl.