我有以下数组:
ifNameList -> $VAR1 = [
{
'VALUE' => ' gpon_olt-1/1/1',
'ASN1' => '285278465'
},
{
'VALUE' => ' gpon_olt-1/1/2',
'ASN1' => '285278466'
},
{
'VALUE' => ' gpon_olt-1/1/3',
'ASN1' => '285278467'
},
{
'VALUE' => ' gpon_olt-1/1/4',
'ASN1' => '285278468'
},
{
'VALUE' => ' gpon_olt-1/1/5',
'ASN1' => '285278469'
},
]我需要迭代这个哈希数组,比较每个散列的"VALUE“字段,直到它匹配并执行一些操作。
我已经编写了以下代码,但它不起作用。我做错什么了?
sub GetIfIndexFromName{
my $ifName = shift;
my @ifList = shift;
my $index;
for (@ifList){
my %interfaceHash = %$_;
# Just trims any blank space on the string:
$interfaceHash->{"VALUE"} =~ s/^\s+|\s+$//g;
if($interfaceHash->{"VALUE"} eq $ifName){
print "trimmed interface name-> ".$interfaceHash->{"VALUE"}."\n\n";
$index = $interfaceHash->{"ASN1"};
}
}
print "Returning index value: ".$index;
return $index;
}发布于 2022-07-06 20:30:55
两个错误。
问题1:错误变量
始终使用use strict; use warnings;。它会发现这个错误:
# Access the `VALUE` element of the hash referenced by `$interfaceHash`.
$interfaceHash->{"VALUE"}您没有名为$interfaceHash的变量。
有三种方法可以解决这个问题:
for ( @ifList ) {
my %interfaceHash = %$_;
... $interfaceHash{ VALUE } ...
}for my $interfaceHash ( @ifList ) {
... $interfaceHash->{ VALUE } ...
}建议采用后者。它避免创建散列的副本,该副本涉及创建多个临时标量。这都是无用的工作。
问题2:不正确的参数检索
以下是错误的:
my @ifList = shift;shift返回一个标量。使用数组在任何时候都准确地保存一个标量是没有意义的。
sub GetIfIndexFromName {
my $ifName = shift;
my $ifList = shift;
for ( @$ifList ) {
...
}
}
# Pass a reference to the array.
GetIfIndexFromName( $ifName, $VAR1 )sub GetIfIndexFromName {
my $ifName = shift;
my @ifList = @_;
for ( @ifList ) {
...
}
}
# Pass each element of the array.
GetIfIndexFromName( $ifName, @$VAR1 )前者的效率更高,但后者可以在调用方中创建更干净的代码。但可能不在你的节目里。
我是怎么写这个的
use strict;
use warnings;
use feature qw( say );
use List::Util qw( first );
sub trim_inplace { $_[0] =~ s/^\s+|\s+\z//g; }
my @ifList = ...;
my $ifName = ...;
trim_inplace( $_->{ VALUE } ) for @ifList;
my $match = first { $_->{ VALUE } eq $ifName } @ifList
or die( "Interface not found.\n" );
my $asn1 = $match->{ ASN1 };
say $asn1;https://stackoverflow.com/questions/72889073
复制相似问题