in reply to Find duplicate chars in a string

sub has_dup_letters { local $_ = shift; tr/a-zA-Z//cd; tr/A-Z/a-z/; my %dups; scalar grep $dups{$_}++ for split //; }

-- Randal L. Schwartz, Perl hacker


code fix: Durnit. replace:
scalar grep $dups{$_}++ for split //;
with
scalar grep $dups{$_}++, split //;
I've been in "postfix for" mode for some reason.

Replies are listed 'Best First'.
Re: Re: Find duplicate chars in a string
by CheeseLord (Deacon) on Oct 14, 2001 at 09:01 UTC

    Um... that code doesn't compile, nor does it do the same thing as the original code. This is my version (it could use whatever error checking you might want on the user-supplied alphabet, though):

    sub has_dup_letters { local $_ = lc shift; my $alpha = @_ ? shift : 'a-z'; eval "tr/$alpha//cd"; my (%dups, $total); $dups{$_}++ and $total++ for split //; return $total; }

    His Royal Cheeziness

      eval "tr/$alpha//cd";
      That can be evil if $alpha contains a slash or is untrusted. To do that tr right requires some really careful thinking.

      That's why I conveniently ignored all but the basic specification. {grin}

      -- Randal L. Schwartz, Perl hacker

Re: Re: Find duplicate chars in a string
by Fletch (Bishop) on Oct 14, 2001 at 18:35 UTC
    ## ITYM scalar grep $dups{$_}++, split //;