Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keys that spring into existence if checked with exists [duplicate]

If a perl-hash is declared like so:

use warnings;
use strict;

my %h;

I can then check for the existence of keys within this hash with exists:

if (exists $h{k3}) {
  print "k3 exists\n";
}
else {
  print "k3 doesn't exist\n";
}

Since k3 does not exist, the script prints k3 doesn't exist.

I can also check for the existence ka in k3:

if (exists $h{k3}{ka}) {
  print "k3 ka exists\n";
}
else {
  print "k3 ka doesn't exist\n";
}

Unfortunately, this creates the key k3, so that another

if (exists $h{k3}) {
  print "k3 exists\n";
}
else {
  print "k3 doesn't exist\n";
}

now prints k3 exists.

This is a bit unfortunate for my purposes. I'd rather not want perl to create the k3 key.

I can, of course, check for ka within k3 with something like

if (exists $h{k3} and exists $h{k3}{ka})

which doesn't create the key k3. But I wonder if there is a shorter (and imho cleaner) way to check for ka within k3.

Edit The question was marked as duplicate. Unfortunately, the only answer in the referred question that mentions no autovivification has only one upvote there, and is not marked as accepted answer. For my purposes, the no autovification is the feature I needed to know (and that I was unknowingly after). So, I leave my question here as I think the accepted answer in the other question is not the optimal one.

Unfortunatly, nobody so far answered with no autovification which I would like to accept. I might therefore answer my own question.

like image 572
René Nyffenegger Avatar asked Jun 04 '13 20:06

René Nyffenegger


People also ask

Are duplicate keys allowed in HashMap?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

Which collection can have duplicate keys?

You cannot do it by Java collection. You can use Multimap it supports duplicate keys but it also support duplicate keys and value pairs. Best solution for you is use Multimap and check if value already exist then dont add it.

Can map have duplicate keys Java?

Overview. The map implementations provided by the Java JDK don't allow duplicate keys. If we try to insert an entry with a key that exists, the map will simply overwrite the previous entry.

How do I find duplicate keys on a map?

Keys are unique once added to the HashMap , but you can know if the next one you are going to add is already present by querying the hash map with containsKey(..) or get(..) method.


1 Answers

The simplest thing is to nest your ifs:

if (exists $h{k3}) {
  print "k3 exists\n";
  if (exists $h{k3}{ka}) {
    print "k3 ka exists\n";
  }
  else {
    print "k3 ka doesn't exist\n";
  }
}
else {
  print "k3 doesn't exist\n";
}
like image 86
Marc Shapiro Avatar answered Oct 02 '22 00:10

Marc Shapiro