如何在 Perl 中表示集合?
我想用 Perl 表示一个集合。我通常做的是使用带有一些虚拟值的哈希,例如:
my %hash=();
$hash{"element1"}=1;
$hash{"element5"}=1;
然后使用 if (define $hash{$element_name})
来确定元素是否在集合中。
这是常见做法吗?有什么改进的建议吗?
另外,我应该使用define
还是exists
?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,以这种方式构建哈希集是一种常见的习惯用法。请注意:
优于使用
1
作为值,因为undef
占用的空间要少得多。这也迫使您使用exists
(无论如何,这是正确的选择)。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).使用 CPAN 上的众多 Set 模块之一。从您的示例来看,
Set::Light
或Set::Scalar
似乎合适。我可以用 CPAN 的常用论点来捍卫这一建议(不考虑可能的协同效应)。
很少有事实证明一开始就选择一个模块是错误的选择。
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.
我一直都是这样做的。我倾向于使用
exists
而不是define
但它们都应该在这种情况下工作。That's how I've always done it. I would tend to use
exists
rather thandefined
but they should both work in this context.