develooper Front page | perl.perl5.porters | Postings from July 2019

I would love to write: overloaded string operators

Thread Next
Paul "LeoNerd" Evans
July 3, 2019 11:32
I would love to write: overloaded string operators
Message ID:
((A followup to my message
  Subject: Metathread - Programs I would love to write

I would love to write

  use Hypothetical::POD::Parser;
  use String::Tagged::Terminal;
  use Text::Wrap qw( wrap );

  my $text = Hypothetical::POD::Parser->parse("some_file.pod");

  $text = wrap("", "", $text);


This would be nice, as it combines two useful modules:

  * String::Tagged and its various subclasses provide an object class
    that stores a string along with name/value extents within it.
    The hypothetical parser module would return one of these to contain
    the formatting information parsed out of the given POD file.
    String::Tagged::Terminal then uses those to render the formatting
    to the terminal.

  * Text::Wrap conveniently splits paragraphs of text at word
    boundaries, wrapping it into lines no wider than the terminal, so
    words are not split in the middle. It makes nicely printed output.

However, currently this program does not work as expected. The
String::Tagged instance passed in to wrap() gets converted down to a
plain perl string by its stringification operator, losing all the
formatting. The output that gets printed contains the right words, but
has lost all its formatting information.

(There's nothing particular about Text::Wrap in this example - any
text-handling CPAN module would do this. I am just using Text::Wrap as
a simple example here).

This problem is due to the fact that Text::Wrap is written using
regular perl string operations like split(), substr(), regexp matches
and join(), which do not have ways to define operator overloading.
Before I get into more detail on that, I first want to establish the
overall theme for this thread; namely that:

  We believe that providing operator overloads for core string
  operators like split(), substr(), regexps and join() is a useful
  ability to try to achieve.

(Compare to all of the number operator overloads like addition, sqrt()
and sin(), for example)

If we generally agree it'd be nice to be able to write this sort of
thing, then I'll expand more on why it currently doesn't work, why I
believe p5p are the place to begin solving it, and then we can work on
how to fix it.

(There has previously been some discussion on this issue with respect
 to join(), but it got derailed into a minor complication of
 stringification vs. concat operators.

Paul "LeoNerd" Evans      |  |

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About