简体   繁体   English

数组与Perl有何不同?

[英]How different are arrays from Perl?

I can create 2-d arrays in Perl. 我可以在Perl中创建二维数组。 How different is 2d arrays from Hash? 2d数组与Hash有何不同? Why is hash a primitive data structure in perl, when we can simulate the hash features using arrays? 当我们可以使用数组模拟哈希功能时,为什么在perl中哈希是原始数据结构?

Probably you mean you can have a data structure like this: 也许您的意思是您可以拥有这样的数据结构:

my $array_hash = [
  [ "key1", "value1" ],
  [ "key2", "value2" ],
];

For small data this works well, but consider the case that such an array has about 1000 entries. 对于小数据,此方法效果很好,但请考虑这种数组具有约1000个条目的情况。 Then, to find a specific entry by its key, you have to search through the whole array, which is slow. 然后,要通过键查找特定条目,您必须搜索整个数组,这很慢。

The primitive hash type allows for quick lookups, and this is exactly what it is used for. 原始哈希类型允许快速查找,这正是它的用途。

Another reason that hash tables are built into Perl is that they are useful data structures, so not every programmer should need to implement his own. 哈希表内置在Perl中的另一个原因是它们是有用的数据结构,因此并非每个程序员都需要实现自己的哈希表。

In construction of many types of objects, the new method can be passed a list of arguments that may appear as a hash, but it really is just an array, where every even number is a key, and every odd number is a value. 在构造许多类型的对象时,可以向new方法传递一个可能显示为哈希的参数列表,但实际上它只是一个数组,其中每个偶数是一个键,每个奇数是一个值。

my $obj = Some::New::Class->new(
  name => 'Sam',
  age  => 0,
  email => 'sam@localhost'
);

This is the equivalent to: 这等效于:

my $obj = Some::New::Class->new(
  'name', 'Sam',
  'age', 0,
  'email', 'sam@localhost'
);

You can, however, instruct new() to look for a hash, which would appear more like: 但是,您可以指示new()查找哈希,该哈希看起来更像是:

my $obj = Some::New::Class->new({
  name => 'Sam',
  age  => 0,
  email => 'sam@localhost'
});

If this doesn't answer your question, I hope I at least provided some insight. 如果这不能回答您的问题,我希望至少提供一些见识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM