Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

String replacement

by wallacei (Initiate)
on Jul 21, 2005 at 13:36 UTC ( #476824=perlquestion: print w/replies, xml ) Need Help??
wallacei has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I would like to place "-" into string A based on the position they are in string B.
Basic Idea: ABABA goes to AB--A-BA based on template BB--B-BB
I can do this just by looping over the two strings, as below, but I am wondering if there is a neat perl way of doing it with out using loops? Thanks for your guidance!
my $j =0; for($i=0;$i<length($protein);$i++){ my $chr=substr($protein,$i,1); if($chr ne "-"){ $new_dna=$new_dna.substr($dna,$j,1); $j=$j+1; }else{ $new_dna=$new_dna."-"; } + + + }

Replies are listed 'Best First'.
Re: String replacement
by Tanalis (Curate) on Jul 21, 2005 at 14:30 UTC
    Probably not the best way to do it, but this works:
    my $a = "ABABA"; my $b = "BB--B-BB"; $b =~ s/B/\%c/g; printf $b, unpack 'c*', $a;
    Gets rid of the loop, at least *grin*.
Re: String replacement
by Roy Johnson (Monsignor) on Jul 21, 2005 at 18:53 UTC
    This is the same as what you're doing, but using s/// to walk the template.
    my $a = "ABABA"; my $b = "BB--B-BB"; my $new = $b; my $a_pos = 0; $new =~ s:[^-]:substr($a, $a_pos++, 1):ge; print "New is $new\n";
    Update: I like this better. Inserting hyphens at corresponding points:
    my $a = "ABABA"; my $b = "BB--B-BB"; substr($a, pos($b)-1, 0, '-') while ($b =~ /-/g); print "A is now $a\n";

    Caution: Contents may have been coded under pressure.
Re: String replacement
by radiantmatrix (Parson) on Jul 21, 2005 at 20:15 UTC

    Yet another WTDI:

    my ($string_a, $string_b) = ('ABABA','BB--B-BB'); my @a = split '',$string_a; my @b = split '',$string_b; $string_a = ''; my $a_ndx = 0; for (0..@b-1) { $string_a .= $b[$_] eq '-' ? '-' : $a[$a_ndx++] }

    This particular version modifies the 'A' string, but it could be trivially modified to preserve that string and build a fresh one; I consider that an advantage, but YMMV.

    Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
    The Code that can be seen is not the true Code
    "In any sufficiently large group of people, most are idiots" - Kaa's Law

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://476824]
Approved by Tanalis
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2018-10-20 00:52 GMT
Find Nodes?
    Voting Booth?
    When I need money for a bigger acquisition, I usually ...

    Results (111 votes). Check out past polls.

    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!