On 4/18/05, N. Ganesh Babu wrote:
> Dear All
>
> I want to do capitalisation of this text. I am using the following code.
> It works fine with all other lines.
>
> $line="Level A (Grade 1 reading level)";
>
> @words=split(/ /,$line);
> for($i=0;$i<=$#words;$i++)
> {
> $words[$i]=~s!($words[$i])!\u\L$1!gi;
> print "$words[$i]\n";
> }
>
Hi Ganesh,
There is a Perl builtin function called "ucfirst" that does what you
want (read "perldoc -f ucfirst"), but I also wanted to point out that
your code is very "un-perlish". Specifically:
> @words=split(/ /,$line);
> for($i=0;$i<=$#words;$i++)
There is no need to keep the result of split in a temporary array
(@words), nor iterate over the array using a c-style "for" loop.
Simple iterate over the results of the split:
for (split /(\s+)/, $line) { ...code... }
Inside the for loop (is actually a "foreach" loop, but the two
keywords are interchangable in Perl), the special variable $_ will
hold the current word returned by split.
If you look at my split usage, you will notice I wrote the pattern
"/(\s+)/" inteead of "/ /". It is better to split of "one or more
whitespace" instead of on a "single space", incase your string might
include something like "word (two spaces) word". Read "perldoc -f
split" for details.
In addition, I return the whitespace as part of the results, so that
the string will not look different (in terms of whitespace) when I
print it out. Here is the complete code:
########## begin code
use strict;
use warnings;
my $line="Level A (Grade 1 reading level)";
my $ucline = "";
for (split /(\s+)/,$line )
{
$ucline .= ucfirst($_);
}
print "$ucline\n";
########## end code
Of course this means the ucfirst function will also operate on
whitespace, but this doesn't do any harm.
HTH,
--
Offer Kaye
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>