in reply to get first e.g. 5 words and replace the remaining string with ... with one regex
That's kind of an odd requirement. Is this homework? It makes more sense to just extract the first five words and then append whatever you want. The way you posed it awkward and should be reframed.
Hmmm... on further thought the expanded code with the conditional really just looks like a plain replacement. I've added a second code block where I turn this into a substitution.
The original code. This will clobber $text if there are less than five words.
# Capture the first five words including whitespace. ($text) = $text =~ / (\S+ \s+ \S+ \s+ \S+ \s+ \S+ \s+ \S+ )/x; # Shrink any internal whitespace $text =~ s/\s+/ /g;
The amended code to compensate for the previous block's clobbering action
# Capture the first five words including whitespace. if ( $text =~ / (\S+ \s+ \S+ \s+ \S+ \s+ \S+ \s+ \S+ )/x ) { # The regex extracted the first five words $text = "$1 ..."; # Shrink any internal whitespace $text =~ s/\s+/ /g; }
That previous block really looked like a substition. Here it is, reframed again
if ( $text =~ s/ (\S+ \s+ \S+ \s+ \S+ \s+ \S+ \s+ \S+ )/$1 .../x ) { # The match succeeded, shrink the white space $text =~ s/\s+/ /g; }
Updated Altered $text .= "whatever" to $text .= " ...". Also added caveats on word count
Seeking Green geeks in Minnesota
|
|---|