4 ms·
I like D's approach of using `d[$]` to get the last element, `d[$-1]` to get the element before last, etc.
by gnuvince 4y ago
I like D's approach of using `d[$]` to get the last element, `d[$-1]` to get the element before last, etc.
- david2ndaccount 4y ago`$` refers to the length of the array, so `d[$]` is an array-bounds error. `d[$-1]` is needed for the last element, but you can’t do that blindly, you have to check that the length is nonzero or you’ll get unsigned underflow to ulong.max
- WalterBright 4y agoWhich will also cause an array-bounds error. So you're covered!
- melagonster 4y agoperl have $d[$#d] represent the index of last element.
- bvrmn 4y ago$my_properly_named_array[$#my_properly_named_array] doesn't look like QoL.
- tmtvl 4y agoYeah, but $#list is better used for writing loops: foreach my $i (0..$#list) { say "$i: $list[$i]"; } For getting the last element from a list you can just use -1 (and of course further negative numbers work like you would expect, -2 is second to last and so on): my @last_three = @items[-1, -2, -3];
- melagonster 4y agoyes, I forgot perl have negative index!