Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

The Regex Approach: Merging 2 strings like a zip

by pat_mc (Pilgrim)
on Jul 11, 2015 at 11:59 UTC ( [id://1134298]=note: print w/replies, xml ) Need Help??


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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1134298]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-03-29 14:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found