Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • I'm still a bit in golf mode, but here's a possibility:
    $uniq_chars = keys %{{ split /()/, $string }};
    • Odd number of elements in anonymous hash at line 5.

      It doesn't like having an odd number of characters in the string length. Looks like the basis for what I was after, so some tweaking might be in order.

      Thanks for the suggestion.

      • Oops, I forgot to turn on warnings when I ran the one-liner (told you I was in golf mode!). Actually it gives the warning even if the string has an even number of characters. Here's a variation:
        $uniq_chars = keys %{{ $string =~ /(.)()/gs }};
        • I thought I'd do a bit of benchmarking and was rather surprised at the results.

          This was the code:

          #!/usr/bin/perl -w
          use strict;

          use Benchmark qw(:all);

          my $string = "ABCDEEsdasdasdfsadfwewasdaSD";

          cmpthese(100000, {
              'foreach' => \&do_foreach,
              'map' => \&do_map,
              'split' => \&do_split,

          sub do_foreach {
              my %hash;
              foreach ( split //, $string ) { $hash{$_}=1; }
              my $uniq_chars = keys %hash;

          sub do_map {
              my %hash;
              map {$hash{$_}=1} split //, $string;
              my $uniq_chars = keys %hash;

          sub do_split {
              my $uniq_chars = keys %{{ $string =~ /(.)()/gs }};
          With the following results:
                     Rate   split foreach     map
          split   10000/s      --    -15%    -20%
          foreach 11830/s     18%      --     -5%
          map     12475/s     25%      5%      --
          The map snippet was what I was using, so it looks like I made the right choice. Always good to see other ways of doing it. So it was still a useful exercise.