Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Spliting a sentence 1

Status
Not open for further replies.

math

Programmer
Mar 21, 2001
56
0
0
BE
Hi,

I want to spilt a sentence but KEEP the points,questionmarks,spaces,...

Like so:
$sentence = "A simple sentence!";
@words = spilt(/???/,$sentence);

@words[0] should be 'A'
@words[1] should be ' '
@words[2] should be 'simple'
@words[3] should be ' '
@words[4] should be 'sentence'
@words[5] should be '!'

But I have no idea how the expression should be??
just the words is simple, but I want to keep the '!' !!!
the ' ' don't really matter, but could be usefull to me... Can anyone help?

Thanx ALOT !!
math
 
Math,

Would something like this help?

Code:
#!/usr/bin/perl -w
use strict;

my $sentence = "A simple sentence!";
my @words = split /(\w{1,})/, $sentence;
my $element;
my $count = 0;
foreach $element (@words) {
   print "Element ", $count++, ": $element\n"; }

On my system, it prints the following:

Code:
C:\work\perl>perl split1.pl
Element 0:
Element 1: A
Element 2:
Element 3: simple
Element 4:
Element 5: sentence
Element 6: !

Hope this helps...
 
By the way, I screwed up a bit. Don't use split to break apart the sentence. Use:

Code:
   my @words = ( $sentence =~ /(\w+|\s+|[[:punct:]]+)/g );

instead; otherwise, you'll get a leading entry in your array.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top