首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Perl中遍历散列数组?

如何在Perl中遍历散列数组?
EN

Stack Overflow用户
提问于 2022-07-06 19:43:48
回答 1查看 49关注 0票数 0

我有以下数组:

代码语言:javascript
复制
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“字段,直到它匹配并执行一些操作。

我已经编写了以下代码,但它不起作用。我做错什么了?

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2022-07-06 20:30:55

两个错误。

问题1:错误变量

始终使用use strict; use warnings;。它会发现这个错误:

代码语言:javascript
复制
# Access the `VALUE` element of the hash referenced by `$interfaceHash`.
$interfaceHash->{"VALUE"}

您没有名为$interfaceHash的变量。

有三种方法可以解决这个问题:

代码语言:javascript
复制
for ( @ifList ) {
   my %interfaceHash = %$_;
   ... $interfaceHash{ VALUE } ...
}
代码语言:javascript
复制
for my $interfaceHash ( @ifList ) {
   ... $interfaceHash->{ VALUE } ...
}

建议采用后者。它避免创建散列的副本,该副本涉及创建多个临时标量。这都是无用的工作。

问题2:不正确的参数检索

以下是错误的:

代码语言:javascript
复制
my @ifList = shift;

shift返回一个标量。使用数组在任何时候都准确地保存一个标量是没有意义的。

代码语言:javascript
复制
sub GetIfIndexFromName {
    my $ifName = shift;
    my $ifList = shift;
   
    for ( @$ifList ) {
       ...
    }
}

# Pass a reference to the array.
GetIfIndexFromName( $ifName, $VAR1 )
代码语言:javascript
复制
sub GetIfIndexFromName {
    my $ifName = shift;
    my @ifList = @_;
   
    for ( @ifList ) {
       ...
    }
}

# Pass each element of the array.
GetIfIndexFromName( $ifName, @$VAR1 )

前者的效率更高,但后者可以在调用方中创建更干净的代码。但可能不在你的节目里。

我是怎么写这个的

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72889073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档