my $chars = q{abcde}; # Specify the characters. my $matchset = "[$chars]"; # Set up a character class. my $reg_match = qr{$matchset}; # Turn it into a regexp. my @strings = qw/ apple logs frog elmo /; foreach my $string ( @strings ) { print "$_ matched\n" if $string =~ $reg_match; } __END__ apple elmo #### my $matchset = "[^$chars]"; # <-- Changed to a negated char class. # .... foreach my $string ( @strings ) { print "$_ is pure" if not $string =~ $reg_match; # Disqualify strings with illegal chars. } #### package Multiset; use strict; use warnings; sub new { my $class = shift; my %self; $self{set_chars} = shift; my $neg_char_class = "[^$self{set_chars}]"; $self{set_regexp} = qr/$neg_char_class/; $self{entries} = {}; bless \%self, $class; } sub is_valid { my $self = shift; my $string = shift; return 0 if $string =~ $self->{set_regexp}; # Contains bad chars. return 1; } sub _normalize { my $self = shift; my $string = shift; return( join '', sort split //, $string ); } sub is_unique { my $self = shift; my $string = shift; my $normalized = _normalize( $self, $string ); return 0 if exists $self->{entries}{$normalized}; return 1; } sub add_entry { my $self = shift; my $string = shift; die "Invalid entry." unless is_valid( $self, $string ); my $entry = _normalize( $self, $string ); return 0 unless is_unique( $self, $entry ); $self->{entries}{$entry}++; } sub remove_entry { my $self = shift; my $string = shift; my $entry = _normalize( $self, $string ); die "Invalid entry." unless is_valid( $self, $entry ); die "Entry doesn't exist." if not is_unique( $self, $entry ); delete $self->{entries}{$entry}; return 1; } sub list_seen { my $self = shift; return keys $self->{entries}; } 1; package main; use strict; use warnings; my @strings = qw/ ab ac ca bb dc abc cba /; my $set = q/abcde/; my $multi = Multiset->new( $set ); foreach my $string ( @strings ) { print "$string\n"; if( $multi->is_valid( $string ) ) { print "\tis valid.\n"; } else { print "\tis not valid.\n"; next; } if( $multi->is_unique( $string ) ) { print "\tis unique.\n"; $multi->add_entry( $string ); } else { print "\tis not unique.\n"; } } my @found = $multi->list_seen(); print "Entries:\n\t@found\n"; #### ab is valid. is unique. ac is valid. is unique. ca is valid. is not unique. bb is valid. is unique. dc is valid. is unique. abc is valid. is unique. cba is valid. is not unique. Entries: ab cd abc bb ac