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

Three loops, but only one or two will ever iterate:

#! perl -slw use strict; sub truncTo { my( $s, $t ) = @_; my $l = length $s; $s =~ m[^\s*(.+?)\s*$]; my( $b, $e ) = ( $-[1], $+[1] ); ++$e while $e < $l and ( $e - $b ) < $t; --$b while $b 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: Truncate string to limited length, throwing away unimportant characters first.
  • Download Code

Replies are listed 'Best First'.
Re^2: Truncate string to limited length, throwing away unimportant characters first.
by ikegami (Patriarch) on Mar 16, 2010 at 21:04 UTC
    Practically all the tests failed. You are removing spaces from the beginning before removing spaces from the end.

      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.