3

splice

Is it OK, when OFFSET is within the array but the end of LENGTH is past the end of the array?

sid_com
  • 24,137
  • 26
  • 96
  • 187

2 Answers2

2

Easy to try.

$ perl -wE'
   my @a = "a".."e";
   my @b = splice @a, 2, 10;
   say 0+@b, " elements were removed.";
   say 0+@a, " elements remain."
'
3 elements were removed.
2 elements remain.

I have every confidence that this will not change.

ikegami
  • 367,544
  • 15
  • 269
  • 518
1

It seems valid. The doc say anything about this scenario. The below code illustrates that length past the boundary is valid.

@array = ('this','is','for','testing','this','is','for','testing');
@array1 = (1,2,3,4,5,6,7,8,9,10);


splice @array,5,100,@array1;

print join "\n", @array ;
tuxuday
  • 2,977
  • 17
  • 18
  • 1
    Make a habit of using `use strict` and using code that is strict-compliant, i.e. `my @array = ...`. Also, it would serve you well to remember certain perl idioms, such as `my @array = qw(this is for testing this is for testing)` and `my @array1 = 1..10`. If your perl version is >= 5.10, you can use `use v5.10; say for @array`. – TLP May 11 '12 at 12:53
  • this is just a sample script, as such didn't warrant for **strict** et all. I missed **qw()** as was programming in many other languages. I agree those are valid points. – tuxuday May 11 '12 at 13:01
  • 1
    Since the only cost of using `strict` is a few more characters to type, and the gain is insurance against a great many trivial errors, I would say that there is never really any good reason to not `use strict`. Except possibly in one-liners. And if that does not appeal to you, consider the fact that using strict is such a good idea that your up- and downvotes sometimes rely on it. – TLP May 11 '12 at 13:24
  • If one knows what **use strict** for or for that matter **perl -w** then one knows when to use it and when not to. The fact that the functionalities of **use strict** aren't enforced in perl by default validates it. – tuxuday May 11 '12 at 13:33
  • It seems valid. But could someone say - if the code breaks in some future release - why did you use `splice` in way not documented? – sid_com May 11 '12 at 14:00
  • @tuxuday Except that 99% of the reasons to not use strict and warnings is laziness. And a misguided laziness, at that, because not using these two pragmas will actually cause you more work in the long run. – TLP May 11 '12 at 14:07
  • @sid_com In what way is it not documented? – TLP May 11 '12 at 14:08
  • @tuxuday See this question for more info http://stackoverflow.com/q/8023959/725418 – TLP May 11 '12 at 14:32
  • @TMP In the sense, that I didn't see something where it is described what happens, when the end of `LENGTH` is past the end of the array. – sid_com May 11 '12 at 15:36