Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

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

by LanX (Canon)
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.

UPDATE:

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?

UPDATE:

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


Comment on Re: compare two strings and return only he unique values.
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2015-07-29 05:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (260 votes), past polls