开发者

How different are arrays from Perl?

I can create 2-d arrays in Perl. How different is 2d arrays from Hash? Why is hash a primitive d开发者_如何学Cata structure in perl, when we can simulate the hash features using arrays?


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


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.

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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜