http://www.perlmonks.org?node_id=1063584


in reply to checking the string against all values of multidimension hashmap in perl

Perhaps the following will be helpful:

use strict; use warnings; my %hash; my @interfaceSampleAliases = ( "AFGHD_NORTH", "NORTHERN_IIDID_IPV123", "IDL_SOUTH", "IDL_SOUTH_IUID", "SOUTHERN_IND_IPV", "IDL_NORTH_IPV", "IDL_ABDGJF" ); chomp( my @iniFileData = <DATA> ); initInterfaceAliasHash( \%hash, \@iniFileData ); for my $interface (@interfaceSampleAliases) { if ( my $key = findInterfaceAlias( \%hash, \$interface ) ) { print "'$interface' matches key: $key\n"; } else { print "'$interface': No match\n"; } } sub initInterfaceAliasHash { my ( $hashRef, $iniFileDataRef ) = @_; my $i = 1; for (@$iniFileDataRef) { my @ands; my ( $key, $val ) = split /=/; my @ors = split /\|\|/, $val; for my $or (@ors) { push @ands, join '', map { "(?=.*\\b\Q$_\E\\b)" } split /, +/, $or; } $$hashRef{ $i++ }{$key} = join '|', map { "(?:$_)" } @ands; } } sub findInterfaceAlias { my ( $hashRef, $interfaceAliasRef ) = @_; my $lastMatch = 0; my $interfaceAlias = $$interfaceAliasRef; $interfaceAlias =~ s/_/ /g; for my $key1 ( sort { $a <=> $b } keys %$hashRef ) { my $key2 = ( keys $$hashRef{$key1} )[0]; $lastMatch = $key1 if $interfaceAlias =~ /$$hashRef{$key1}{$key2}/ and $key1 > $lastMatch; } return ( keys $$hashRef{$lastMatch} )[0] if $lastMatch; } __DATA__ MANAGEMENT=IDL||CIDL NORTH_IPV=IDL,NORTHERN||VIDL,NORTH||IDL,NORTH SOUTH_IPV=IDL,SOUTHERN||CIDL,SOUTH||IDL,SOUTH

Output:

'AFGHD_NORTH': No match 'NORTHERN_IIDID_IPV123': No match 'IDL_SOUTH' matches key: SOUTH_IPV 'IDL_SOUTH_IUID' matches key: SOUTH_IPV 'SOUTHERN_IND_IPV': No match 'IDL_NORTH_IPV' matches key: NORTH_IPV 'IDL_ABDGJF' matches key: MANAGEMENT

All subroutines take references. The subroutine initInterfaceAliasHash() takes a hash reference and an array reference. The array reference is a reference to an array that holds the chomped lines of the ini file. The hash of hashes (HoH) that's built uses the order of the lines as keys to Interface Aliases as keys and the associated values that are regexes which do the and/or logic. Here's a Dumper of the hash that created above:

$VAR1 = { '1' => { 'MANAGEMENT' => '(?:(?=.*\\bIDL\\b))|(?:(?=.*\\bCID +L\\b))' }, '3' => { 'SOUTH_IPV' => '(?:(?=.*\\bIDL\\b)(?=.*\\bSOUTHERN\ +\b))|(?:(?=.*\\bCIDL\\b)(?=.*\\bSOUTH\\b))|(?:(?=.*\\bIDL\\b)(?=.*\\b +SOUTH\\b))' }, '2' => { 'NORTH_IPV' => '(?:(?=.*\\bIDL\\b)(?=.*\\bNORTHERN\ +\b))|(?:(?=.*\\bVIDL\\b)(?=.*\\bNORTH\\b))|(?:(?=.*\\bIDL\\b)(?=.*\\b +NORTH\\b))' } };

To check an Interface Alias, send a hash reference and a reference to the string that holds the Interface Alias to the subroutine findInterfaceAlias(). If there was a match, the key from the last successful match will be returned, else NULL is returned.