Forum Moderators: coopster & phranque

Message Too Old, No Replies

Non-unique key in associative array

         

csdude55

12:07 am on Nov 21, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I originally began with this:

###
$first = param('original');
$second = param('second');

%arr = (
'yellow' => 'blue',
'red' => 'green'
);

if ($arr{$first} eq $second || $arr{$second} eq $first) { $filter = 1; }
###

So if $first is "yellow" and $second is "blue", OR if $first is "blue" and $second is "yellow", then $filter will be set.

In practice, I have about 70 keys. But over time, I'm having to deal with duplicate possibilities. So in theory, I wrote this:

###
%arr = (
'yellow' => 'blue',
'yellow' => 'green',
'yellow' => 'red',

'red' => 'green'
);

if ($arr{$first} eq $second || $arr{$second} eq $first) { $filter = 1; }
###

But of course, this doesn't work because $arr{'yellow'} now equals "red", so "blue" or "green" would no longer match. And I can't just reverse it, because the values duplicate, too ("green" is a value for both "yellow" and "red").

I believe that I can fix it with a hash of arrays, so something like:

###
%arr = (
yellow => {
'blue' => 1,
'green' => 1,
'red' => 1
},

red => {
'green' => 1
}
);

if ($arr{$first}{$second} || $arr{$second}{$first}) { $filter = 1; }
###

Before I implement this, (1) do you guys see any problem with my coding, and (2) can you suggest a better / more readable way to do what I'm trying to do?

csdude55

2:51 am on Nov 21, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Update... no, that doesn't quite work. The second part is the issue:


$arr{$second}{$first}


So if $first = 'red' and $second = 'green', it's not going to match.

I guess that I could make a second hash and invert all of the keys => values in a loop, but that seems like a pain and can't be the best option. Like this:


# Not tested, just typed for this post
%arr = (
yellow => {
'blue' => 1,
'green' => 1,
'red' => 1
},

red => {
'green' => 1
}
);

if ($arr{$first}{$second}) { $filter = 1; }

if (!$filter) {
my %arr2;

foreach $key (keys %arr) {
foreach $key2 (keys %arr{$key}) {
$arr2{$key2}{$key} = 1;
}
}

if ($arr2{$first}{$second}) { $filter = 1; }
}


Any other suggestions?