How can I represent sets in Perl?

后端 未结 3 808
闹比i
闹比i 2020-12-05 13:09

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\         


        
3条回答
  •  孤街浪徒
    2020-12-05 13:50

    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).

提交回复
热议问题