Re: Both Methods and Indexing for Objects?
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxx
- Date: 31 Jul 2007 13:59:38 GMT
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__
.
- References:
- Both Methods and Indexing for Objects?
- From: Veli-Pekka Tätilä
- Both Methods and Indexing for Objects?
- Prev by Date: Both Methods and Indexing for Objects?
- Next by Date: Re: threads and logfile rotation
- Previous by thread: Both Methods and Indexing for Objects?
- Index(es):
Relevant Pages
|