Re: Both Methods and Indexing for Objects?



Veli-Pekka Tätilä <vtatila@xxxxxxxxxxxxxxxxxxxx> wrote in comp.lang.perl.misc:
Hi,
I'd like to treat an object like an array but also provide methods for
accessing bits of the object state that aren't array-like. An example in
which this would be useful comes from Ruby, its regexp Match objects are
indexable like arrays for accessing back references, yet they also have
a nice interface via methods. Can Perl also do objects having both
methods and hash or array-like indexing?

You can overload de-referencing in your class. That won't make objects
look like arrays, but like array references, which may be good enough.

I've made up a Regex class that behaves a bit like what you describe.
After a match, an object can be used like an array ref that holds
the captured strings (with the entire match in array position 0).

Anno

-----------------------------------------------------------------------

my $r = Regex->new( '(.)(.)(.)');
$r->match( 'abc');

print "$r->[ $_]\n" for 1 .. 3;
print "@$r\n";


package Regex;

sub new {
my ( $class, $re) = @_;
bless { re => qr/$re/, capt => [] }, $class;
}

sub match {
my ( $r, $str) = @_;
@{ $r->{ capt} } = $str =~ /($r->{ re})/;
return scalar @{ $r->{ capt} };
}

use overload '@{}' => sub { shift()->{ capt} };
__END__
.



Relevant Pages

  • Re: Is it possible to have parameters in a property?
    ... possible to expose its elements with "array-like" syntax through a ... property without exposing the full array, ...     get ... to pass the index and value as parameters rather than using array-like ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: IsArray?
    ... As the docs (for IsArray) state: "The Array class returns false ... you can't have an instance of just Array, and various array-like ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Group names in regular expressions
    ... Is there a regex.method to access the parse data by group name? ... extend the regex class with my own method. ... using this code and suitable data, "array" will contain: ... Paul Lutus ...
    (comp.lang.ruby)