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.
| input | output |
|---|---|
| " 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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |