Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: splicing two arrays together

by TJPride (Pilgrim)
on Jan 06, 2012 at 05:08 UTC ( #946524=note: print w/replies, xml ) Need Help??

in reply to splicing two arrays together

use strict; use warnings; my @first = qw(Can unlock secret); my @second = qw(you the code?); splice(@first, $_+1, 0, $second[$_]) for reverse 0..$#second; print "@first\n";

I notice this is fairly close to one of GrandFather's solutions, but that's really because there is only one best way to do this if the requirement is to use splice.

Replies are listed 'Best First'.
Re^2: splicing two arrays together
by GrandFather (Sage) on Jan 06, 2012 at 06:22 UTC

    This is a trivial variant of one of the three different splice based options I provided. So which of the trivial variations is "the one best way" to do it? How is this "the best way" if preserving the content of @first is desired? What non-artificial context would require the use of split?

    Remember an oft quoted virtue of Perl is TIMTOWTDI with the strong implication that there is seldom a "single best solution". Actually even with languages that tout themselves as offering the "one true way" there is seldom a single "best" solution to any problem.

    True laziness is hard work
      Thanks Grandfather for those solutions, the best solution I guest is the one that requires the least amount of typing in any language?

        I'd say the best solution is the one that works correctly, is maintainable and fast enough. Number of lines or characters of code is generally one of the least important criteria. The most important criteria depends a great deal on the purpose of the code.

        True laziness is hard work
        Well, it depends. The best solution might be the one that runs fastest, uses minimal memory, or the one that can be easily understood for later maintenance.
      Actually, it's an independent solution that just happens to be mostly identical to yours. My determination of "best" is that the OP asked for a solution with splice, and this was the best solution possible with splice. Obviously, splice is not the most efficient way to do this overall, but that's the OP's problem, since he framed the question in the context of splice rather than the context of finding the most efficient way to do merge two arrays. I'm guessing it's a homework problem and they said he had to use splice.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://946524]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2018-02-18 00:27 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (250 votes). Check out past polls.