Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: extracting only those keys with uniq values in array list

by davido (Cardinal)
on Apr 20, 2021 at 15:50 UTC ( #11131517=note: print w/replies, xml ) Need Help??


in reply to extracting only those keys with uniq values in array list

In your question you should post an example of the data structure you are working with. Your description says that you are dealing with a hash of arrays, and that for every key there are two values. In some cases those two values are the same, and in other cases they are not. Since you're using substr in your example, I'll assume that "the same" means stringwise equality.

I'm imagining that your datastructure looks like this:

my %hash = ( foo => ['this', 'that'], # Two different values bar => ['those', 'those'], # Two identical values baz => ['the', 'other'], # Not the same buzz => ['same', 'same'], # The same );

In this structure you would want to print the name of the bar key and buzz key, since the values in the array ref for those keys are the same. You didn't suggest that there could ever be more or less than two values, so I won't solve the problem that isn't stated. Here's an example of how to accomplish what you're after given this data structure:

my %hash = ( foo => ['this', 'that'], # Two different values bar => ['those', 'those'], # Two identical values baz => ['the', 'other'], # Not the same buzz => ['same', 'same'], # The same ); while (my ($key, $aref) = each %hash) { if ($aref->[0] eq $aref->[1]) { print "$key\n"; } }

The output now should be 'bar' and 'buzz'.

If there could be fewer than two elements to compare, you could do this:

if (2==@$aref && $aref->[0] eq $aref->[1]) ...

If there could be more than two, and you want to assure that they are all equal, you could do this:

while (my ($key, $aref) = each %hash) { my %seen; $seen{$_}++ for @$aref; next if 1 != keys %seen; print "$key\n"; }

If these scenarios don't match the problem you are trying to solve, please refine your question to remove the ambiguity that has resulted in a diverse selection of answers.


Dave

Replies are listed 'Best First'.
Re^2: extracting only those keys with uniq values in array list
by v15 (Sexton) on Apr 20, 2021 at 16:36 UTC
    Very well represented example and explanation. Thank you

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11131517]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (1)
As of 2021-05-14 04:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Perl 7 will be out ...





    Results (148 votes). Check out past polls.

    Notices?