develooper Front page | perl.perl5.porters | Postings from June 2010

join() and split() to respect string overload operations

Thread Next
From:
Paul LeoNerd Evans
Date:
June 4, 2010 08:35
Subject:
join() and split() to respect string overload operations
Message ID:
20100604153529.GR11110@cel.leo
Having created a string buffer-alike class, String::Tagged, it supports
a concat operation, meaning that

 $foo . $bar

still yields a String::Tagged object with all the tags in place. I've
been thinking about how to make join() respect the string concat
operator of any objects it's passed in, to ensure that

  join $sep, @list == reduce { $a.$sep.$b } @list

even in the face of objects with overloads. That doesn't seem too hard.

But now it occurs to me; in plain strings there's an invariant between

  $str = join $sep, $a, $b, $c;
  ( $a, $b, $c ) = split m/^Q$sep/, $str;

So for this, it would be nice if a split $re, $str could observe some
magic on the $str object and act accordingly. split() is really a "find
the cut points, then map substr() over it". So if we could define a
substr() overload operation on an object, then split() could use this to
extract its substrings.

I wonder therefore, whether we should consider substr() to be somewhat
of an operator, for the purposes of allowing overload to apply on it.

 package MyStrings;
 use overload 'substr' => 'SUBSTR';

 sub SUBSTR
 {
    my $self = shift;
    my ( $offs, $len ) = @_;

    ...

    return "Some part";
 }

The details here would need some consideration - would the offset and
length be passed as-is from the substr(), or be converted somehow?

And, given as substr() can yield an LVALUE, how do we handle
modifications? Get the SUBSTR method to return some LVALUEish result, or
invoke SUBSTR a second time once someone supplies a replacement?

 sub SUBSTR
 {
    my $self = shift;
    if( @_ == 3 ) {
       my ( $offs, $len, $new ) = @_;
       ...
    }
    else {
       my ( $offs, $len ) = @_;
       ...
       return $part;
    }
 }

-- 
Paul "LeoNerd" Evans

leonerd@leonerd.org.uk
ICQ# 4135350       |  Registered Linux# 179460
http://www.leonerd.org.uk/

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About