Forum Moderators: coopster & phranque

Message Too Old, No Replies

Display only a certain number of words in a string

         

maccas

5:19 pm on Aug 11, 2005 (gmt 0)

10+ Year Member



Hi, I have a string but I only want to diplay x number of words, any pointers?

KevinADC

7:59 pm on Aug 11, 2005 (gmt 0)

10+ Year Member



you could split the line on spaces and display only the elements you want.

my $string = 'this is a line with some words';
my @words = split(/\s+/,$string);
print "$_ " for @words[0..4];

will print only the first 5 words. Are you sure you want to display x number of words and not x number of characters/bytes?

maccas

8:33 pm on Aug 11, 2005 (gmt 0)

10+ Year Member



Thanks KevinADC, worked a treat. What about by character, an example of this would be excellent as I have been pulling my hair out searching for either way.

WWMike

2:35 am on Aug 12, 2005 (gmt 0)

10+ Year Member



Use the substr function:

[perldoc.perl.org...]

KevinADC

4:48 am on Aug 12, 2005 (gmt 0)

10+ Year Member



yes, substr() is also what I would suggest.

a simple example:

my $string = 'This is a line with some words';
print substr $string,0,20;

will print the first 20 characters, spaces included.

Read the link WWMike posted for more details.