mehul wrote:
hi all,
i am just starting with PERL and had this doubt related to the speical
operator +.
what it says is that in the line split( / +/,$line);
it will not ignore the initial spaces as it starts a word when it
encounters a space...
so if possibly there is only a single space in the staring,then it
shldnt be a problem isnt it?
and also if there are more than 1 spaces then it says that also the
word count would be 1 more than the total no of words.but what i think
is that it will simply count the spaces in continuation with the first
word and so the first word would have the spaces, but the count will
remain the same.
hope someone will clear this point for me.
mehul.
Here's the output for my test:
Count for no space was 2
Count for one space was 3
Count for five spaces was 3
Here's the code that produced the output.
#!/usr/bin/perl -w
my $line = 'no space';
@results = split / +/, $line;
$count = @results;
print "Count for no space was $count\n";
$line = " One space";
@results = split / +/, $line;
$count = @results;
print "Count for one space was $count\n";
$line = " Five spaces";
@results = split / +/, $line;
$count = @results;
print "Count for five spaces was $count\n";
In this case the pattern for split is read as one or more spaces. By
default in regular expressions + is greedy. So in the second case one
leading space qualified as as a word because one space satisfied / +/
and in the third case 5 spaces counted as a single word because + means
one or more. I hope this code clarifies the point for you.
Allan