Skip to content

Very API

June 25, 2010
tags: , ,

In my last post about extending autobox::Core, I touched on API choices. So let me expand on this a little bit here and in some more in posts to come.

In all bar one of my autobox examples I used $_[0] to pass the iterator object. For eg:

['a'..'z']->iterate( sub{
    print $_[0]->currentIndex, ' => ', $_[0]->current;

But in the last code example I went for $_[0] having the value and $_[1] the iterator object:

['a'..'z']->iterate( sub{
    print $_[1]->currentIndex, ' => ', $_[0];

And to help avoid getting cross-eyed with $_[] then this is nicer on the eye if a tad longer:

['a'..'z']->iterate( sub{
	my ($v, $iter) = @_;
    print $iter->currentIndex, ' => ', $v;

But hold on, is there a preference to which way round these should be assigned to @_? Would it be better other way round because value can be got at from the iterator object anyway? (one shift and away!)

So perhaps using $_ is best?

['a'..'z']->iterate( sub{
    print $_->currentIndex, ' => ', $_->current;

I like this a lot. But it would be amiss not to take advantage of using $_ for the value and $_[0] for iterator so that we can write code like this:

['a'..'z']->iterate( sub{
	print $_[0]->getNext if m/[aeiou]/;

However note the print $_[0]->getNext and not just plain print :(

I don’t think there is a canonical answer to this but my preference is to use $_ has the iterator object… but with probably value & the iterator (again!) passed through @_ (ie. the kitchen sink approach!).

sub autobox::Core::ARRAY::iterate {
    my ($array, $code) = @_;
    my $iter = Array::Iterator->new( $array );
    while ($iter->hasNext) {
        local $_ = $iter;
        $code->( $iter->getNext, $iter );

    return wantarray ? @$array : $array;

Note the return wantarray ? @$array : $array; addition. This keeps the autobox chaining going and is good adherence to autobox API (though in this iterator context it probably isn’t of much benefit).


PS. Let me just add “Perl” here because despite lots of perl code snippets I haven’t mentioned Perl, CPAN or Ironman at all and I’m still wary whether ironman will pick up the perl tag.

One Comment leave one →
  1. August 1, 2010 8:55 am

    I would like to exchange links with your site
    Is this possible?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: