in reply to Merge 2 strings like a zip

"TIMTOWTDI"

My 2 ¢:

use warnings; use strict; use feature qw(say); sub zip; say zip 'ABCDEFGHIJ', 'abcde'; sub zip { join "", sort { lc $a cmp lc $b } split "", $_[0] . $_[1]; } __END__

I guess it's slower than some of the examples above but it doesn't look bad ;-)

And i learned something. See Strange Observation [SOLVED] for details. Thanks to toolic, KurtSchwind, Athanasius and some unknown soldier.

Update: Same benchmark as used by BrowserUK:

karls-mac-mini:monks karl$ ./benchzip.pl Rate B Karl A C B 98641/s -- -17% -44% -68% Karl 118153/s 20% -- -33% -62% A 176987/s 79% 50% -- -43% C 312785/s 217% 165% 77% --

Regards, Karl

«The Crux of the Biscuit is the Apostrophe»

Replies are listed 'Best First'.
The Regex Approach: Merging 2 strings like a zip
by pat_mc (Pilgrim) on Jul 11, 2015 at 11:59 UTC
    While in principle I would agree with the statement that there is no need to re-write existing functionality from modules (= re-inventing the wheel), I would argue strongly in favour of the striving for elegance in coding. Questions like this one have an immense value as they inspire the quest for a concise and elegant solution thus fostering an in-depth understanding of Perl's inner workings. Anyway, so much for the philosophical part of my post.

    Here's my code solution now. It essentially achieves the zipping in one single line of code (if you are lenient enough not to count the conversion of one input string into a list). Lemme know what you think.

    use strict; use warnings; my $a = "ABCDEFGHIJ"; my $b = "abcde"; my @b = split "", $b; $a =~ s/(.)/$1.($b[length($`)] or "")/ge; print $a;

      You'll need a // operator there, otherwise it eats the 0's in $b...

      An alternative:

      $b = reverse $b; $a =~ s{.\K}{chop $b}sge; print $a;

Re^2: Merge 2 strings like a zip
by tel2 (Pilgrim) on Jul 12, 2015 at 23:44 UTC
    Thanks for that, Karl.

    It seems to work with my original sample data, but with this:
       say zip 'ABCDEFGH0J', 'a0cde';
    it produces this:
       00AaBCcDdEeFGHJ
    but should be producing this:
       AaB0CcDdEeFGH0J