Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: compare two strings and return only he unique values.

by LanX (Chancellor)
on Feb 03, 2013 at 22:44 UTC ( #1016873=note: print w/replies, xml ) Need Help??

in reply to compare two strings and return only he unique values.

please use real <code> tags and not &lt;code&gt;

looks like you want the symmetric difference of two character sets

DB<111> @a1=split//,$str1 => ("A", "B", "C", "D", "E") DB<112> @a2=split//,$str2 => ("B", "C", "D", "E", "O") DB<113> @h2{@a2}=() DB<114> @h1{@a1}=() DB<115> delete @h2{@a1} DB<116> delete @h1{@a2} DB<117> (keys %h1, keys %h2) => ("A", "O")

see Using hashes for set operations... for background.


seems like nobody mentioned that its a FAQ How do I compute the difference of two arrays? How do I compute the intersection of two arrays?


Just in case you only want the unique characters in both strings:

DB<137> $h{$_}++ for (split//,$str1),(split//,$str2) => "" DB<138> \%h => { A => 1, B => 2, C => 2, D => 2, E => 2, O => 1 } DB<139> grep {$h{$_}==1} keys %h => ("A", "O")

oops basically already shown by Not_a_Number

EDIT: one liner =)

DB<146> grep {$h{$_}==1} map {$h{$_}++;$_} split//,$str1.$str2 => ("A", "O")

Cheers Rolf

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016873]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2017-08-23 14:55 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (353 votes). Check out past polls.