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:
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With