CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: Re: [psynt555] Regex to compare (if) two strings (Uniquely - I will explain inside): Edit Log



rovf
Veteran

Nov 26, 2012, 1:17 AM


Views: 1930
Re: [psynt555] Regex to compare (if) two strings (Uniquely - I will explain inside)

To verify, that a string contains only unique letters, you can use an arcane feature found in the tr operator in Perl. Assume that the string to check is stored in variable $x and that $x doesn't contain a forward slash (how to deal with this special case, is left as an exercise for you ;-). Now calculate the following:


Code
$_=$x;  
eval "tr/$x/./d";
say "The string /$x/ doesn't contain only of unique characters"
if length < length($x);


The basic idea is to make a copy of the string and delete duplicate characters in the copy. If the new string is shorter than the old one, at least one character must have been duplicated.

Deleting duplicates is a side effect of the tr/// operator. tr is mainly used for translating one character set into another one, and the 'd' modifier causes duplicates to be removed. In our case, we are not interested in the translation proper, but only in the side effect done by 'd'.

See perldoc perlop for details.


(This post was edited by rovf on Nov 26, 2012, 1:18 AM)


Edit Log:
Post edited by rovf (Veteran) on Nov 26, 2012, 1:18 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives