[英]Return array of hashes in perl
The below function logins into a router, executes a command to get the IPsec session status and returns the interface name and ip address as string. 下面的函数登录到路由器,执行命令以获取IPsec会话状态,并以字符串形式返回接口名称和IP地址。 Instead of returning a string, I want the function to return array of hashes.
我希望函数返回哈希数组,而不是返回字符串。 Can someone help me out with that ?
有人可以帮我吗?
sub cryptoSessionStatus {
my ($self,$interface) = @_;
my $status = 0;
my $peer_ip = 0;
#command to check the tunnel status
my $cmd = 'command goes here ' . $interface;
#$self->_login();
my $tunnel_status = $self->_login->exec($cmd);
#Regex to match the 'tunnel status' and 'peer ip' string in the cmd output
#Session status: DOWN/UP
#Peer: x.x.x.x
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_obj = test::Cryptotunnels->new('host'=> 'ip');
my $crypto_sessions = $tunnel_obj->cryptoSessionStatus("tunnel1");
This should do it: 应该这样做:
my @session_states;
my $status;
foreach my $line ( $tunnel_status ) {
if ( $line =~ m/Session\s+status:\s+(.*)/ ) {
$status = $1;
}
if ( $line =~ m/Peer:\s+(\d+.\d+.\d+.\d+)/ ) {
push @session_states, { ip => $1 , status => $status };
$status = ""
}
}
return \@session_states;
#
# called like so
#
my $tunnel_obj = test::Cryptotunnels->new('host'=> 'ip');
my $crypto_sessions = $tunnel_obj->cryptoSessionStatus("tunnel1");
for my $obj (@$crypto_sessions) {
print $obj->{ip}, "\n";
print $obj->{status}, "\n";
}
This assumes the Session status
line appears before the Peer
line in the output. 假定
Session status
行出现在输出中的Peer
行之前 。 If its the other way around (you didn't supply a sample of what the router output looks like, so I have to guess a bit...) ie: if the Peer
line is before the Session status
line then it should be like this: 如果是相反的情况(您没有提供路由器输出的样例,那么我不得不猜测一下...),即:如果
Peer
行位于Session status
行之前,那么它应该像这个:
my @session_states;
my $peer_ip;
foreach my $line ( $tunnel_status ) {
if ( $line =~ m/Session\s+status:\s+(.*)/ ) {
push @session_states, { ip => $peer_ip , status => $1 };
$peer_ip = "";
}
if ( $line =~ m/Peer:\s+(\d+.\d+.\d+.\d+)/ ) {
$peer_ip = $1;
}
}
return \@session_states;
#
# called the same as above
#
There's no real difference in the algorithm - whichever comes second in the output - Peer
or Session status
- defines the end of the entry and a hash is created with the two entries and pushed onto the @session_states
array. 算法没有真正的区别-输出中的第二位-
Peer
或Session status
-定义条目的末尾,并使用这两个条目创建哈希并将其推入@session_states
数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.