Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Compare two strings of same length, character-by-character

by davido (Cardinal)
on Nov 29, 2023 at 23:15 UTC ( [id://11155954]=note: print w/replies, xml ) Need Help??


in reply to Compare two strings of same length, character-by-character

Another option, that is mostly straightforward...

#!/usr/bin/env perl use strict; use warnings; use List::Util qw(zip); my $str1='LFGSLSIIVAHHM'; my $str2='LFGSLSIIVSHHM'; my ($s1len, $s2len) = map {length} ($str1, $str2); die "Length mismatch: $str1 ($s1len) != $str2 ($s2len).\n" if $s1len != $s2len; my $match = grep {$_->[0] eq $_->[1]} zip [split //, $str1], [split //, $str2]; my $mismatch = $s1len-$match; print "Matches: $match\nMismatches: $mismatch\nPercent match: ", sprintf("%.01f", ($match / $s1len) * 100), "\n";

The output is:

Matches: 12 Mismatches: 1 Percent match: 92.3

This uses List::Util, which is a core Perl module, and aside from the slightly mysterious 'zip', reads like how a person would think through the problem; compare the first letter, compare the second, compare the third, and so on. No real magic that would require a #comment


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (2)
As of 2025-12-07 16:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (86 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.