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

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

问题描述

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

  my%hash =(); 
$ hash {element1} = 1;
$ hash {element5} = 1;

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



这是一种常见的做法吗?还有,如果我使用定义存在 code>?



谢谢

解决方案

CPAN上的许多Set模块。从你的例子来看, Set :: Light Set :: Scalar 似乎是合适的。






我可以用通常的CPAN参数来防御这个建议(不考虑可能的协同效应)。


  1. 我们如何能够知道查找是现在还是未来所需要的?经验告诉我们即使是最简单的程序也会扩展和蔓延。使用模块会预料到这一点。

  2. API的维护要好得多,或者需要阅读和理解代码的人,而不是特殊的实现,因为它允许考虑关于不同抽象层次的部分问题。
  3. 与此相关,如果事实证明开销不理想,那么通过去除间接或削减来简化从模块到简单数据结构和源代码。但另一方面,如果需要更多的功能,实现其他方式则更为困难。

  4. CPAN模块已经过测试并在一定程度上彻底调试过,可能还有该API随着时间的推移而经历了改进步骤,而通过临时的,程序员通常实施第一个想到的设计

很少发现在开始时选择模块是错误的选择。

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

解决方案

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

  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天全站免登陆