in reply to Re^2: Truncate string to limited length, throwing away unimportant characters first.
in thread Truncate string to limited length, throwing away unimportant characters first.

Whoops! I got the order reversed in my mind. All that's needed is to reverse the ordering of the first two loops:

#! perl -slw use strict; sub truncTo { my( $s, $t ) = @_; my $l = length $s; $s =~ m[^\s*(.+?)\s*$]; my( $b, $e ) = ( $-[1], $+[1] ); --$b while $b and ( $e - $b ) < $t; ++$e while $e < $l and ( $e - $b ) < $t; --$e while ( $e - $b ) > $t; return substr( $s, $b, $e-$b ); } for( " ab ", " ab ", " abc ", " abcd ", " abcde ", " abcdef ", " abcdefg ", ) { printf "%15.15s => '%s'\n", "'$_'", truncTo( $_, 6 ); } __END__ c:\test>828994.pl ' ab ' => ' ab ' ' ab ' => ' ab ' ' abc ' => ' abc ' ' abcd ' => ' abcd' ' abcde ' => ' abcde' ' abcdef ' => 'abcdef' ' abcdefg ' => 'abcdef'

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"I'd rather go naked than blow up my ass"
  • Comment on Re^3: Truncate string to limited length, throwing away unimportant characters first.
  • Download Code