Home > Perl6 > Hashes are containers too

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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: