When solving word puzzles it is often handy to check if a string has duplicate letters in it. Here is a quick function to do that.

If you want to check for dups that are broader (letters, numbers punctuation) or narrower (eg just vowels) than just normal letters you can supply your own alphabet.

For illustration purposes the function is dropped in to a trivial program.

#!/usr/local/bin/perl my $dups = &has_dup_letters (@ARGV); if ($dups) { print "There is/are $dups dup(s).\n"; } else { print "There are no dups.\n"; } sub has_dup_letters { # Takes a word and optionally an alphabet. # Returns the number of duplications (0 for none). eg abc # Returns the number of duplications are measured as letters remov +ed to # make it unique. eg abbc == 1; abbbc == abbcc ==2; # Characters not in the alphabet are ignored regardless of # duplication. # If you do not supply an alphabet it will use a-z. If you wanted # to check different characters (vowels) or numbers or punctuation +, # just include them in your alphabet. # Case of A-Z is ignored. Trailing \n of words are chomped. my ($word, $alphabet) = @_; unless ($alphabet) { $alphabet = 'abcdefghijklmnopqrstuvwxyz' }; $alphabet_size = length $alphabet; chomp $word; # down case it $word =~ tr/A-Z/a-z/; # Remove chars not in the alphabet. $word =~ s/[^$alphabet]//g; $alphabet =~ s/[$word]//g; unless ((length($alphabet) + length($word)) == $alphabet_size) { length ($alphabet) + length ($word) - $alphabet_size; # has du +ps } else { 0; # No Dups } }

In reply to Find duplicate chars in a string by monkfish

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.