develooper Front page | perl.perl5.porters | Postings from April 2000

Re: [ID 20000424.006] split() returning incorrect number of fields

Thread Previous | Thread Next
Ronald J Kimball
April 24, 2000 15:01
Re: [ID 20000424.006] split() returning incorrect number of fields
Message ID:
On Mon, Apr 24, 2000 at 05:48:50PM -0400, Adam Moskowitz wrote:

> In the following program, I contend that split() should return the same
> number of fields in both cases:
> 	my $str1 = "aaa:bbb:ccc:ddd:eee";
> 	my $str2 = "aaa:bbb:ccc:ddd:";
> 	my @w;
> 	@w = split(/:/, $str1);
> 	printf("scalar(\@w) = %d\n\n",scalar(@w));
> 	@w = split(/:/, $str2);
> 	printf("scalar(\@w) = %d\n",scalar(@w));
> It doesn't. I'm pretty sure that this is neither the correct nor
> expected behavior.

I think you missed the relevant part of the documentation on split:

    If LIMIT is specified and positive, splits into no more than that many
    fields (though it may split into fewer).  If LIMIT is unspecified or
    zero, trailing null fields are stripped (which potential users of
    C<pop()> would do well to remember).  If LIMIT is negative, it is
    treated as if an arbitrarily large LIMIT had been specified.

The second sentencce explains that trailing null fields, as in your second
string above, will be stripped.  But, the third sentence hints at how to
get your desired result:

      @w = split(/:/, $str2, -1);
      printf("scalar(\@w) = %d\n",scalar(@w));


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About