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

Practically all the tests failed. You are removing spaces from the beginning before removing spaces from the end.
  • Comment on Re^2: Truncate string to limited length, throwing away unimportant characters first.

Replies are listed 'Best First'.
Re^3: Truncate string to limited length, throwing away unimportant characters first.
by BrowserUk (Patriarch) on Mar 16, 2010 at 21:54 UTC

    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.