Array::AsHash

Ovid on 2005-10-14T16:44:21

I just uploaded Array::AsHash 0.11. Unfortunately, 0.10 fails the tests because I omitted the test libraries in the MANIFEST. Whoops.

This module lets you treat an array as a hash.

my $array = Array::AsHash->new({ array => \@array });
my $val = $array->get($key);
$array->put($key, $new_val);

my $count = $array->hcount; # number of key/value pairs
my $count = $array->acount; # number of array elements

$array->put($object, $value);
print $array->get($object); # References as keys are allowed

@array = $array->get_array;

In addition to including the test libs, I've added a number of other features that have proven quite handy. Amongst other things, there are now first and last methods which only return true when on the corresponding key/value pairs in an each loop:

my $array = Array::AsHash->new({array => [qw/foo bar one 1 two 2/]});

while (my ($k, $v) = $array->each) {
  print "Starting loop\n" if $array->first;
  print "Key is $k.  Value is $v\n";
  print "Ending loop\n"   if $array->last;
}

I've also provide a default method which sets values if an only if the corresponding key does not exist in the array. There are also a bunch of "array-like methods" which allow you to push, shift, etc., onto the array and still treat it like a hash.

I've been converting a bunch of code over to use this new module and it's really cleaned things up quite a bit.


Re:

Aristotle on 2005-10-15T16:24:36

my $array = Array::AsHash->new({array => [qw/foo bar one 1 two 2/]});

while (my ($k, $v) = $array->each) {
  print "Starting loop\n" if $array->first;
  print "Key is $k.  Value is $v\n";
  print "Ending loop\n"   if $array->last;
}

That makes me think Adrian was right that the iterator should be factored out.

Nice work, in any case. I think I can think of a script or two which would have been nicer to write with code like that. Perl’s builtin data types are powerful, but things get really fiddly if you need something more than they can express natively.

Re:

Ovid on 2005-10-15T17:17:27

I'm need to do some more work on this module today. I think I will look into the iterator.