Logo

Programming-Idioms

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

Idiom #277 Remove an element from a set

Remove the element e from the set x.

Explains what happens if e was already absent from x.

use strict;
use Set::Scalar;
my $set = Set::Scalar->new( 'a' .. 'f' );

print "Contents of set:\n";
print $set;

$set->delete('b','e');

print "\nAfter removing elements b and e:\n";
print $set;

Use CPAN Set::Scalar (or Set::Light) to create a set object, which in this example we initialize with letters. We can then use the delete method to delete one or more elements from the set.
@x = grep $e ne $_, @x;

Array is not technically a set since it allows for repeat values. Either you are enforcing uniqueness or you should use a module like Set::Light
use strict;
my %set;
my @list = ( 'a' .. 'f' );
$set{$_} = 1 for @list;

delete $set{'c'};	# delete specific key

use v5.20;
delete %set{'a','e'}	# delete hash slice

This implementation uses a perl hash %set to act as a set, since keys to a hash must be unique. A list is created to hold the keys, then the hash is initialized from it. The delete operation can delete a specific key. As of version 5.20, you can also delete a hash slice.
(disj x e)

Removing a non-existent element from a set returns back an identical set.

New implementation...