perl split function

$mystring = "name:blk:house::";
print "$mystring\n";
@s_format = split(/:/, $mystring);

for ($i=0; $i <= $#s_format; $i++) {
print "index is $i,field is $s_format[$i]";
print "\n";
}
$size = $#s_format + 1;
print "total size of array is $size\n";

i am expecting my size to be 5, why is it only 3?

That's an interesting observation of the idiosyncracies of the Perl split() function. From the manpage, the first paragraph reads:

It appears strange to me too ... I am not sure if there is a workaround of it.

i agree with cbkihong !!! You could therefore ensure that the last field contains something < != "" > basically not equal to nil .....

i would add something like this to check for it :

$mystring = "name:blk:house::end";
print "$mystring\n";
@s_format = split(/:/, $mystring);

for $i (0 .. $#s_format)
{
if (@s_format[$i] == "") {print "index is ",$i," nothing !\n"; }
else {print "index is $i,field is $s_format[$i]\n";}
}
$size = $#s_format + 1;
print "total size of array is $size\n";

If you are not really that much concerned with the REAL number of fields, and you expect a fixed number of fields, you will get the same results nevertheless by directly poking into the array returned.

e.g.

That's probably the cause they put it like that, although it seems to be strange still.

just concat with some other character just before splitting.

$string = "name:blk:house::";
@res = split(/[:]/,$string.".");
print "size of array : $#res";

@s_format = split(/:/, $mystring,10);

Hi all, i added the limiter above, it works. i am not sure of the specifics of the mechanism, but it works.

from the post from cbkihong, i guessed that as long as i make perl think that the trailing empty spaces are not empty, specifying the limit, it works.