Hashes are containers too
Lets say we want to count the occurrence of stuff. The usual way to do so is to have a “seen-hash”. Sometimes we have a known set keys we are looking for, where some may not be contained in the data we scan. That’s a special case, which Perl 6 can handle nicely because Hashes are containers and therefor can have default values.
my $words = <Hashes are containers too>.lc; constant alphabet = 'a' .. 'z'; my %seen of Int is default(0); %seen{$_}++ for $words.comb; put "$_: %seen{$_}" for alphabet;
The special case of a character that is not in $words
, is handled by is default(0)
.
Default values can be quite elaborate. Let’s have one that is 0 in numerical context but stringyfies to NULL
and is always defined.;
my %seen of Int is default(0 but role :: { method Str() {'NULL'} }); say %seen<not-there>, %seen<not-there>.defined, Int.new(%seen<not-there>); # OUTPUT«NULLTrue0»
Categories: Perl6
Comments (0)
Trackbacks (0)
Leave a comment
Trackback