in reply to Check if a word is included in another
One way is to count number of occurrences of characters in a hash:
sub count { my $str = shift; my %h; $h{$_}++ for split //, $str; return \%h; }
Then you can compare those hashes:
sub check { my ($target, $word) = @_; return 0 if length($target) < length($word); my %target = %{ count($target) }; my %word = %{ count($word) }; for (keys %word) { no warnings 'unintialized'; if ($target{$_} < $word{$_}) { print "'$word' can not be made out of letters of '$target', +because it has $word{$_} $_'s\n"; return 0; } } return 1; }
That's a lot longer than your code, but maybe a bit faster if you want to check lots of words against a common target (in which case you can cache %target).
|
|---|