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"}=1;
Then use if (defined $hash{$element_name})
to decide whether an element is in the set.
Is this a common practice? Any suggestions on improving this?
Also, should I use defined
or exists
?
Thank you
Yes, building hash sets that way is a common idiom. Note that:
is preferable to using
1
as the value becauseundef
takes up significantly less space. This also forces you to usesexists
(which is the right choice anyway).Use one of the many Set modules on CPAN. Judging from your example,
Set::Light
orSet::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.
That's how I've always done it. I would tend to use
exists
rather thandefined
but they should both work in this context.