dideod.yang has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks. I need your help :) I want to compare two variable. There are $a = "YAAY" $b = "$YAAA".I want to print only "Y". Only last initial "Y" is different from A to B. Below script, I can compare but I think my script is not that good on performance because of loop. Do you have nice idea? or function?. I have two cases type. case 1 couldn't compare becuase first initial is "Y". but case 2 could compare however I had to use for...I hate loop.. It make performance bad... Please help me Monks :)
use strict; my ($x,$y,@x,@y,$i); # case 1 $x = "YAAY"; $y = "YAAA"; $x =~ s/[$y]+//g; print "$x"; # case 2 $x = "YAAY"; $y = "YAAA"; @x = split(//,$x); @y = split(//,$y); for($i=0;$i<=$#x;$i++){if($x[$i] ne $y[$i]){print "$x[$i]\n"}}

Replies are listed 'Best First'.
Re: variable compare
by tybalt89 (Monsignor) on Jul 13, 2018 at 00:35 UTC
    #!/usr/bin/perl -l # https://perlmonks.org/?node_id=1218408 use strict; use warnings; my $x = "YAAY"; my $y = "YAAA"; print +(($x ^ $y) =~ tr/\0/\xff/cr & $x) =~ tr/\0//dr;
Re: variable compare
by choroba (Cardinal) on Jul 13, 2018 at 06:50 UTC
    How is this question different to your previous one?

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: variable compare
by AnomalousMonk (Archbishop) on Jul 13, 2018 at 01:38 UTC

    Another variation on a theme. All strings assumed to be ASCII strings. All strings do not have to be the same length. Run under Perl version 5.8.9.

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $x = 'YAYBOOAAFUMAAZOT'; my $y = 'YAYFOOAABARA'; ;; my $d = $x ^ $y; dd 'diff string: ', \$d; ;; my @d_seqs; push @d_seqs, [ $-[0], $+[0] - $-[0] ] while $d =~ m{ [^\x00]+ }xmsg; dd 'diff subsequences [offset, len]: ', \@d_seqs; ;; for my $s ($x, $y) { printf qq{'$s' diff subseqs: }; printf qq{'$_' } for map { $_->[0] < length($s) ? substr($s, $_->[0], $_->[1]) : () } +@d_seqs ; print qq{\n}; } " ("diff string: ", \"\0\0\0\4\0\0\0\0\4\24\37\0AZOT") ( "diff subsequences [offset, len]: ", [[3, 1], [8, 3], [12, 4]], ) 'YAYBOOAAFUMAAZOT' diff subseqs: 'B' 'FUM' 'AZOT' 'YAYFOOAABARA' diff subseqs: 'F' 'BAR'
    See "Variables related to regular expressions" in perlvar for  @- @+ arrays. (Update: The  $-[0] $+[0] terms in the code above access elements of the  @- @+ arrays respectively.)


    Give a man a fish:  <%-{-{-{-<

Re: variable compare
by Laurent_R (Canon) on Jul 13, 2018 at 18:56 UTC
    I hate loop.. It make performance bad.
    Not necessarily. And sometimes, code without any explicit loop is still looping implicitly over the items of an array. So don't reject loops too easily.

    Besides, do you really need very high performance? Your code will execute in a tiny split second, why would you want it to go faster (unless, of course, you need to run it on billions of items)?