Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help With Split

Status
Not open for further replies.
Jun 19, 2001
86
0
0
US
Here is an example of my problem:

$data = "hello;world;!;";
@appended = split(/\;/, $data);

When I print $#appended I get 2. Why isn't it 3? I really need the elements of my array to look like:

$appended[0] = hello
$appended[1] = world
$appended[2] = !
$appended[3] = NULL

It seems that perl isn't assigning $appended[3] NULL as I thought it would. Is there any way around this?

Nathan
 
I ran the code you pasted and I get your desired results. My results are:

$appended[0] = hello
$appended[1] = world
$appended[2] = !
$appended[3] = NULL

Everything in your code looks correct to me.

Brandon
 
actually, when I ran the code pasted above, I also did not get the 4th element (null) either. It seems that split cheats, and does not create null elements of the array IF there is nothing following them. So you can put 50 more semicolons in that string in the end - the number of elements is still gonna be 3 there. I don't know why you need the number of elements in the array, but if that is ALL you need, simply count the number of semicolons in a string and add 1.
 
Well I did some more tinkering and found that if you add a limit to split it works correctly. A limit of negative is unlimited. For example.

$data = "hello;world;!;";
@appended = split(/\;/, $data, -1);

Thanks for the input though.

Nathan
 
from perlfunc:
By default, empty leading fields are preserved, and empty trailing ones are deleted...
If LIMIT is unspecified or zero, trailing null fields are stripped...


"As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs."
--Maurice Wilkes
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top