Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #288 Check if set contains a value

Set the boolean b to true if the set x contains the element e, false otherwise.

$b = $x{$e};

Here we are using hash variable %x as a set and assuming that when keys are inserted the corresponding value will be set to a true value; i.e. anything other than undefined or zero.

If the values could be undefined, then it would be necessary to make the expression 'exists $x{$x}'.

Alternatively, use Set::Scalar for real set operations.
b = x.find(e) != x.end();

New implementation...