Bod has asked for the wisdom of the Perl Monks concerning the following question:
In a few places I have code that takes a significant piece of text, such as a knowledgebase article, and splits a small section from the beginning as an abstract. The code I generally use came from an answer to Splitting long text for Template
But now, for a different application, I want to create an abstract of text which may contain HTML tags. The problem comes with not wanting to split an HTML tag in two. I want either all of it or none of it. So this is the code I am using...
It does exactly what I want.sub abstract { my $text = shift; if (length $text > 200 and $text =~ /^(.{0,200}\b)(.*)$/s) { $text = "$1..."; } # Check we have not split an HTML tag my $lt = $text =~ tr/<//; my $gt = $text =~ tr/>//; if ($lt != $gt) { my ($keep, $strip) = $text =~ /(.*)<(.*)/; $text = "$keep..."; } return $text; }
However, I cannot help thinking that the code could be more succinct...
Can you suggest a better way to do it?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Creating an abstract (updated)
by haukex (Archbishop) on Aug 09, 2021 at 22:36 UTC | |
Re: Creating an abstract
by tybalt89 (Monsignor) on Aug 09, 2021 at 21:38 UTC | |
by Bod (Parson) on Aug 09, 2021 at 21:58 UTC | |
by tybalt89 (Monsignor) on Aug 09, 2021 at 22:28 UTC | |
Re: Creating an abstract
by Anonymous Monk on Aug 10, 2021 at 10:14 UTC |
Back to
Seekers of Perl Wisdom