nmerriweather has asked for the wisdom of the Perl Monks concerning the following question:

in the current perl, is it possible to overload arrays or create some sort of class wrapper for arrays ?

i have a module that returns an array. i'd like that array to be blessed into some sort of class that i can call methods on.

python has this, but i've never seen anything like it in perl - so i'm assuming its not possible. just wanted to check.

Replies are listed 'Best First'.
Re: overload arrays ?
by eric256 (Parson) on Feb 08, 2007 at 23:59 UTC

    If an array ref was suitable you could always bless it, then it would be an array AND an object you could call methods on.

    use strict; use warnings; { package Array; sub new { shift @_; my $self = [@_]; bless($self); return $self; } sub joinem { my $self = shift; return join("-", @$self); } } my $test = new Array(1,2,3); print @$test, "\n"; print $test->joinem(), "\n"; __END__ C:\Perl\test>perl array_obj.pl 123 1-2-3

    ___________
    Eric Hodges
Re: overload arrays ?
by Limbic~Region (Chancellor) on Feb 08, 2007 at 23:31 UTC
    nmerriweather,
    I think what you are looking for is perltie. It allows you to create an object that you can treat just like a native data type but you can also call methods on using tied.

    Cheers - L~R

Re: overload arrays ?
by diotalevi (Canon) on Feb 09, 2007 at 00:07 UTC

    There is also autobox.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊