Re: join() and split() to respect string overload operations
[email protected] (Paul LeoNerd Evans)
| Newsgroups | perl.perl5.porters |
|---|---|
| Message-ID | <[email protected]> |
On Sat, Jun 05, 2010 at 08:01:37PM +0300, Yuval Kogman wrote:
> Why not just add a split method to your class? Seems like a lot of work for
> something that is a pretty high level idea anyway.
Well, it already contains a ->substr method.
I suppose I -could- write:
((caveat: untested, but this is the rough idea ;) ))
sub split
{
my $self = shift;
my ( $re ) = @_;
my @points = ( 0 );
while( $self =~ m/$re/g ) {
push @points, $-[0], $+[0]
}
push @points, len $self;
my @ret;
while( @points ) {
my $start = shift @points;
push @ret, $self->substr( $start, shift(@points) - $start );
}
return @ret;
}
However, observe that the -only- line at all relevant to String::Tagged
is the ->substr() line. If Perl were to provide a protocol, an
interface, a way for a subclass to declare "here is my substring
extraction method", then that line could be changed to use that generic
interface, and this entire method can become a useful function for -all-
strings or string-like objects, regardless of where they put their
substring extract method. I observe that use overload substr => $METHOD
would be a convenient way for such a class to tell perl where it keeps
that code.
> With autobox you can even treat your strings and objects as pretty much the
> same thing.
I'm not sure I see how this is relevant in this case.
--
Paul "LeoNerd" Evans
[email protected]
ICQ# 4135350 | Registered Linux# 179460
http://www.leonerd.org.uk/
signature.asc
(application/pgp-signature, 190 B)
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.10 (GNU/Linux) iD8DBQFMDNfLvLS2TC8cBo0RAusmAKDs5ukaCUfKJGQA7YKAYTibDRKN7gCg7cbQ ebrIceIbnBm886PE5foIFsc= =EDGe -----END PGP SIGNATURE-----