I need to make sure that a string is at most 256 characters long. For this, I'd need some perl code that checks if the string is too long, and if it is, it truncates it to at most 256 characters by throwing away whitespace characters from the end of string first, then whitespace characters from the beginning of the string, then any characters from the end of the string.

Do not remove more characters than necessary, so if the string is already at most 256 characters long, then don't remove anything, and if it's longer, then the result shall be exactly 256 characters long.

Here are some examples, assuming for simplicity that I wanted to truncate to 6 characters instead of 256 characters.
inputoutput
"  ab ""  ab "
"  ab   ""  ab  "
"  abc   ""  abc "
"  abcd   ""  abcd"
"  abcde   "" abcde"
"  abcdef   ""abcdef"
"  abcdefg   ""abcdef"

What do you think is the best way truncate an input string this way with some perl code? Below is one solution (again using 6 instead of 256), but it might not be the best one.

Update: the code below was wrong, as ikegami points out in the reply.

It should work now. The bug was that I wrote /\A(\s*)(.*)(\s*)\z/s instead of /\A(\s*)(.*)(\s*)\z/s.

use warnings; use strict; for my $i ( " ab ", " ab ", " abc ", " abcd ", " abcde ", " abcdef ", " abcdefg " ) {
$i =~ /\A(\s*)(.*?)(\s*)\z/s or die; my $o; if (length($1) + length($2) < 6) { $o = substr($i, 0, 6); } elsif (length($2) < 6) { $o = substr($1 . $2, -6); } else { $o = substr($2, 0, 6); }
printf "%-15s%s", qq("$i"), qq( => "$o"\n); } __END__

In reply to Truncate string to limited length, throwing away unimportant characters first. by ambrus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.