如何在 Perl 中表示集合? [英] How can I represent sets in Perl?

查看:35
本文介绍了如何在 Perl 中表示集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Perl 中表示一个集合.我通常做的是使用带有一些虚拟值的散列,例如:

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;

然后使用if(defined $hash{$element_name})来判断一个元素是否在集合中.

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?

另外,我应该使用defined还是exists?

Also, should I use defined or exists?

谢谢

推荐答案

使用 CPAN 上的众多 Set 模块之一.从你的例子来看,Set::LightSet::Scalar 似乎合适.

Use one of the many Set modules on CPAN. Judging from your example, Set::Light or Set::Scalar seem appropriate.

我可以用赞成 CPAN 的通常论据来捍卫这个建议(不考虑可能的协同效应).

I can defend this advice with the usual arguments pro CPAN (disregarding possible synergy effects).

  1. 我们如何知道现在和将来只需要查找?经验告诉我们即使是最简单的程序也会扩展和蔓延.使用模块会预料到这一点.
  2. API 比临时实现更适合维护或需要阅读和理解代码的人,因为它允许考虑不同抽象级别的部分问题.
  3. 与此相关,如果结果证明开销是不可取的,可以通过删除间接或配对数据结构和源代码来轻松地从模块变为简单.但另一方面,如果一个人需要更多功能,则相反地实现它的难度要适中.
  4. CPAN 模块已经过测试,并在某种程度上进行了彻底的调试,也许 API 也随着时间的推移进行了改进,而使用 ad-hoc,程序员通常会实现想到的第一个设计.
  1. How can we know that look-up is all that is needed, both now and in the future? Experience teaches that even the simplest programs expand and sprawl. Using a module would anticipate that.
  2. An API is much nicer for maintenance, or people who need to read and understand the code in general, than an ad-hoc implementation as it allows to think about partial problems at different levels of abstraction.
  3. Related to that, if it turns out that the overhead is undesirable, it is easy to go from a module to a simple by removing indirections or paring data structures and source code. But on the other hand, if one would need more features, it is moderately more difficult to achieve the other way around.
  4. CPAN modules are already tested and to some extent thoroughly debugged, perhaps also the API underwent improvement steps over the time, whereas with ad-hoc, programmers usually implement the first design that comes to mind.

很少会发现一开始就选择一个模块是错误的选择.

Rarely it turns out that picking a module at the beginning is the wrong choice.

这篇关于如何在 Perl 中表示集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆