in reply to Re: Merge 2 strings like a zip
in thread Merge 2 strings like a zip

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;

Replies are listed 'Best First'.
Re: The Regex Approach: Merging 2 strings like a zip
by Anonymous Monk on Jul 11, 2015 at 18:43 UTC

    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;