Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: How to make this substitutions without splitting the strings?

by AnomalousMonk (Archbishop)
on Jul 28, 2014 at 10:42 UTC ( [id://1095327]=note: print w/replies, xml ) Need Help??


in reply to How to make this substitutions without splitting the strings?

(NB: It's not really necessary to post a reeeeealy looooong string to convince us you're dealing with long strings. We're prepared to take your word. Shorter example strings would seem to have been sufficient.)

Insofar as I understand your problem, this is the classic, idiomatic Perlish solution. (I don't know if you really need your  $str1 string transformed also; I do it essentially to support the example.) This approach assumes that  $s1 and  $s2 are always the same length, and also that the null character  \x00 is never a valid part of the  $s1 or  $s2 string.

c:\@Work\Perl\monks>perl -wMstrict -le "my $s1 = '---DAAAGLRG--G--G-P-LT-IGGY'; my $s2 = '...XXXXXXXX..X..X.X.XX.X..X'; print qq{'$s1'}; print qq{'$s2'}; ;; (my $mask = $s1) =~ tr{-\x00-,.-\xff}{\x00\xff}; my $t1 = $s1 & $mask; my $t2 = $s2 & $mask; $t1 =~ tr{\x00}''d; $t2 =~ tr{\x00}''d; ;; print qq{'$t1'}; print qq{'$t2'}; " '---DAAAGLRG--G--G-P-LT-IGGY' '...XXXXXXXX..X..X.X.XX.X..X' 'DAAAGLRGGGPLTIGGY' 'XXXXXXXXXXXXXX..X'

Update: Replaced  s/// with  tr/// in masked character removal step:  $t1 =~ tr{\x00}''d; instead of  $t1 =~ s{ \x00+ }''xmsg;

Replies are listed 'Best First'.
Re^2: How to make this substitutions without splitting the strings?
by Anonymous Monk on Jul 28, 2014 at 12:02 UTC
    Thank you very much, it works like a charm...
    Can you please tell me what does this line:
    (my $mask = $s1) =~ tr{-\x00-,.-\xff}{\x00\xff};
    do? Also, which is the null character?
    Thanks again!
      ... what does this line:

      (my $mask = $s1) =~ tr{-\x00-,.-\xff}{\x00\xff};

      It copies the string  $s1 to the new lexical  $mask while simultaneously translating the characters of  $s1 with the  tr/// function. If you have Perl version 5.14+, you can simplify this statement somewhat by using the  /r modifier:
          my $mask = $s1 =~ tr{-\x00-,.-\xff}{\x00\xff}r;
      See  tr/// in the Quote-Like Operators section in perlop.

      ... which is the null character?

      It is the  \0 character (or byte), hex 0x00, octal 000 (also decimal 0). (Update: Along with its cousin 0xff, it's very useful for creating bit-masks for strings.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-03-28 21:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found