On Thu, Jul 28, 2011 at 3:23 PM, Khabza Mkhize <khabza....@gmail.com> wrote:
> I want to substring words, I might be using wrong terminology. But I tried > the following example the only problem I have it cut word any where it > likes. eg "breathtaking" on my string is only bre. > > > $string = "This is an awe-inspiring tour to the towering headland > known as Cape Point. Magnificent beaches, breathtaking views, historic and > picturesque coastal "; > > $rtioverview = substr ( $string , 0 , 100 ); > > Reults = "This is an awe-inspiring tour to the towering headland known > as Cape Point. Magnificent beaches, bre"; > > > any one can help to solve this problem please? > > -- > > Developer > Green IT Web <http://www.greenitweb.co.za> > http://www.greenitweb.co.za > Using a regular expression can help here... #!/usr/local/bin/perl use strict; use warnings; my $string = "This is an awe-inspiring tour to the towering headland known as Cape Point. Magnificent beaches, breathtaking views, historic and picturesque coastal "; my $num_words = 5; if (my ($words) = $string =~ /((?:\w+(?:\W+|$)){$num_words})/) { print $words; } That should do the trick... you can then very simply pick the number of words you want to return. Another option is to split the thing into the various words and stick that into an array: my @words = split /\W+/, $string; It depends on what you want to do with it of course... also considder doing the following: if (my ($words) = $string =~ /((?:\w+(?:\W+|$)){1..$num_words})/) { print $words; } Which will return you all words from 1 to the total number fo words so if you input strign does not contain the total 100 or 5 or what ever other number of words you are looking for at least you get the words that are found.