note
Eily
<p>Yes, [doc://split] isn't exactly consistent there. There is a third parameter - LIMIT - which limits the number of time the string is splitted. Eg: <c>split '_', 'a_b_c_d', 2</c> will actually return the list ('a', 'b_c_d') because it has been splitted in two.</p>
<p>The thing is if LIMIT is 0 or omitted, all empty fields at the end are removed. So <c>split '_', 'a_b___', 0;</c> will return the list ('a', 'b'). Which is why you get an undefined value in your second case.</p>
<p>Now, the tricky bit is, for optimization, when perl knows how many values you are trying to write to, it will actually set LIMIT to the number of element +1 (split to each element, and ignore the reminder). So
<c>
my ($key, @array[0,1], undef, $value) = split " ", $string;</c> is actually interpreted as <c>
my ($key, @array[0,1], undef, $value) = split " ", $string, 6; # Split five times, ignore the sixth value</c>
In that case, LIMIT is not 0 so the empty fields at the end are not removed.</p>
<p>You could write <c>($key, $value) = split(" ", $string, 8)[0,6];</c> (there are seven values from 0 to 6, so the reminder is the 8th), but the 8 seems to come out of nowhere, and this just calls for a mistake. Luckily, if LIMIT is negative, it will be treated as an infinite value, ie split will continue splitting until the end of the input, and won't remove empty fields at the end:
<c>
my ($key, $value) = (split(" ", $string, -1))[0,6];</c>
Do note that <c>split " "</c> is a special case of split which is the same as <c>split /\s+/</c> except empty fields at the <i>start</i> are removed.</p>
<p>Edit: for what it's worth, [hippo]'s [id://1230553|solution] doesn't have that problem.</p>
1230550
1230565