in reply to Merge 2 strings like a zip

Thanks everyone for your awesome solutions.

Also, since posting my original question, I realised that I forgot to also ask for an unzip function which takes a zipped string and the length of $str2, and generates $str1 & $str2 from it.  I guess I could do it with a verbose style similar to my original function, but would love to see more elegant, concise & efficient options.  Any offers?

I would probably call it something like this:
   ($str1, $str2) = unzip('AaBbCcDdEeFGHIJ', 5);

Thanks again!

Replies are listed 'Best First'.
Re^2: Merge 2 strings like a zip [unzip()]
by kcott (Archbishop) on Jul 09, 2015 at 05:53 UTC

    Based on my earlier zip(): this only uses substr.

    #!/usr/bin/env perl -l use strict; use warnings; print for unzip('AaBbCcDdEeFGHIJ', 5); sub unzip { my ($str1, $len) = @_; my $str2 = ''; for (0 .. $len - 1) { substr $str2, $_, 0, substr $str1, $_ + 1, 1, ''; } return ($str1, $str2); }

    Output:

    ABCDEFGHIJ abcde

    -- Ken

      How dare you put us Kiwis to shame...again, Ken.

      Thanks again and keep up the good work!

      BTW, what's the 'for' for in:
         print for unzip...

        You're welcome.

        Regarding the for statement modifier, I think ++hexcoder has covered most of this in his response.

        That's a fairly common Perl idiom that you're likely to see a lot. In fact, my usage wasn't the first in this thread: BrowserUk's zip() code has '... for split '', $b;'.

        There's a bit more going on behind the scenes.

        • for iterates its list, aliasing $_ to each item in turn (see perlsyn: Statement Modifiers for details)
        • print defaults the filehandle to STDOUT and the list to the single item $_ (that's true in this case but an oversimplification nonetheless: see print for the full story)
        • The '-l' switch (on the shebang line) adds a "\n" to the end of each print statement (again, true in this case but still an oversimplification: see perlrun for the full details of '-l')
        print for unzip('AaBbCcDdEeFGHIJ', 5);

        is equivalent to

        for (unzip('AaBbCcDdEeFGHIJ', 5)) { print STDOUT "$_\n"; }

        -- Ken

        print for unzip('AaBbCcDdEeFGHIJ', 5);

        could be written more explicitly also as

        for (unzip('AaBbCcDdEeFGHIJ', 5)) { print $_; }
        The Perl documentation mentions this here: Statement Modifiers