Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

Ovid
  (email not shown publicly)
http://publius-ovidius.livejournal.com/
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Friday October 14, 2005
11:44 AM

Array::AsHash

[ #27168 ]

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.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • 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 [perl.org] 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

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