If Perl were smarter about references

Reading time: 2 minutes

I wish that Perl 5 could be smarter about references. I wish I could just give an array reference to functions that only act on arrays and have Perl do the dereferencing for me.

Here is what I have to write today to use array functions on an array reference:

# Given $obj->foo() that returns an array reference

shift @{ $obj->foo };
push @{ $obj->foo }, @stuff;
splice @{ $obj->foo }, 0, 2;

Here is how I wish it would work:

shift $obj->foo;
push $obj->foo, @stuff;
splice $obj->foo, 0, 2;

Isn’t that second block a lot cleaner to read? Getting rid of the @{} declutters the code and, at least for me, it’s still clear from the context that I expect the first argument to act like an array.

Likewise, I’d like to have the same magic work for functions like values or keys, which would let me flatten array references or get an index list in a more readable way:

# from this:
for ( @{ $obj->foo } ) { ... }
for ( $#{ $obj->foo } ) { ... }

# to this:
for ( values $obj->foo ) { ... }
for ( keys $obj->foo ) { ... }

I suspect something similar would make sense for hash references, too.

On reflection, I think this would mean that checking that the first argument indeed held an array reference would have to be done at run-time, but I suspect there might be a way within the Perl op-codes to avoid such a checks except when necessary. (Thus, you could still use @{} for a slight bit of hand-optimization, if desired.)

I wish I knew more Perl guts to work on a draft implementation, because right now I think this would be one of the coolest features to see in a future Perl.

•      •      •

If you enjoyed this or have feedback, please let me know by or