I would like to represent a set in Perl. What I usually do is using a hash with some dummy value, e.g.:
my %hash=();
$hash{\"element1\"}=1;
$hash{\"element5\
That's how I've always done it. I would tend to use exists
rather than defined
but they should both work in this context.
Use one of the many Set modules on CPAN. Judging from your example, Set::Light or Set::Scalar seem appropriate.
I can defend this advice with the usual arguments pro CPAN (disregarding possible synergy effects).
Rarely it turns out that picking a module at the beginning is the wrong choice.
Yes, building hash sets that way is a common idiom. Note that:
my @keys = qw/a b c d/;
my %hash;
@hash{@keys} = ();
is preferable to using 1
as the value because undef
takes up significantly less space. This also forces you to uses exists
(which is the right choice anyway).