Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: number of unique characters in a string

by OM_Zen (Scribe)
on Mar 01, 2003 at 04:00 UTC ( #239637=note: print w/ replies, xml ) Need Help??


in reply to number of unique characters in a string

Hi ,

The Hash can hold only unique keys and hence you can store the key as the split string .

my $txt1 = "0101010101"; my $count; my %hashofuniq; my @txt1 = split ('',$txt1); @hashofuniq{@txt1} = 1; foreach (keys %hashofuniq){ $count++; } print "[$count]\n";



Comment on Re: number of unique characters in a string
Download Code
Replies are listed 'Best First'.
Re: Re: number of unique characters in a string
by rob_au (Abbot) on Mar 01, 2003 at 04:08 UTC
    You're on the right track, but I think this could be made more perl-ish again ...

    my $text = '0101010101'; my %hash; @hash{ split '', $text } = 1; print scalar keys %hash, "\n";

     

    perl -le 'print+unpack("N",pack("B32","00000000000000000000001000110111"))'

      ++ for teaching me a new hash syntax tidbit: I never knew about the

      @hash{@list_of_keys} = @list_of_values;

      syntax. Thanks!

      my $text = '0101010101'; my %hash; @hash{ split '', $text } = 1; print scalar keys %hash, "\n";
      Although this code above will work correctly, it will not be doing so the way that you expected which could lead you to trouble.
      @hash{@array} = $scalar
      only sets $scalar as the value for the first key in %hash. To set all the keys, you'd want to do something like:
      @hash{@array} = ($scalar) x scalar @array;
      In the actual code above, since you don't check values anyway, you can just write:
      @hash{@array} = ();

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2015-07-29 23:10 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 (269 votes), past polls