in reply to substr question

Something like this, where a "word" is defined by surrounding whitespace (\s):
use strict; use warnings; my $s = "Hello, I am a perl/mysql programmer, but am self taught so I +do not know all the awesome features Perl has, however, I am ok at it + though, I guess."; my $s2; for (split /\s+/, $s) { $s2 .= "$_ "; last if length($s2) > 100; } print $s2; __END__ Hello, I am a perl/mysql programmer, but am self taught so I do not kn +ow all the awesome features Perl

Replies are listed 'Best First'.
Re^2: substr question
by jwkrahn (Abbot) on Jun 18, 2010 at 18:45 UTC

    Probably better as:

    my $s2; for ( split /(\s+)/, $s ) { last if length( $s2 . $_ ) > 100; $s2 .= $_; } print $s2;
      In fact, your code is worse for 2 reasons:
      • The output string $s2 no longer has any whitespace between words: Hello,Iamaperl/mysql...
      • Generates a warning: Use of uninitialized value $s2...