http://www.perlmonks.org?node_id=1038122


in reply to Re: Using Splice with Two Arrays within a loop
in thread Using Splice with Two Arrays within a loop

Applogies: I have a assignment as follows: "This program can be made both shorter and faster by using a built-in function named splice that will remove a specified number of elements from the @_ array at once, rather than the one-at-a-time that shift does." Using the existing code I need to change it to use splice and have the same exact output. As you can see it is not working. I need some help in this. Thanks
  • Comment on Re^2: Using Splice with Two Arrays within a loop

Replies are listed 'Best First'.
Re^3: Using Splice with Two Arrays within a loop
by hdb (Monsignor) on Jun 10, 2013 at 17:42 UTC

    Be very careful when you ask for "short" code on this website, you might get what you ask for ... ;) like this (meeting your requirement to use splice):

    sub interleave_words { my @results = splice @_, shift; splice @results, 2*$_, 0, shift for 0..@results-1; return @results; }
      Hi thanks for the process however I noticed that the die statement is no longer in the code. I need to include the statement. How do I include that without it printing the die statement instead of the answer I wanted which was Result: Can you unlock the secret code?
      Thanks for the help. Question I still require to keep the die statement in the code however not sure how I put it in without the die statement printing out instead of the correct answer. Thanks for any input

        Now with death build in.

        sub interleave_words { my @results = splice @_, shift; die "Arrays of different size\n" unless @results == @_; splice @results, 2*$_, 0, shift for 0..@results-1; return @results; }