Arrays with unique values

How to get rid of duplicate values in an array in Perl 6?

Note! This site is about Perl 6, the future version of Perl.
If you are looking for a solution for the current production version of Perl 5, please check out the Perl 5 tutorial.
Specifially there is a related article: Unique values in an array in Perl 5.

Arrays with unique values

Basically they show various ways how one can take a list of values and return a sublist of the same values after eliminating the duplicates.

With Perl 6 its quite easy to eliminate duplicate values from a list as there is a built-in called uniq that will do the job.

use v6;

my @duplicates = (1, 1, 2, 5, 1, 4, 3, 2, 1);
say @duplicates.perl;           #, 1, 2, 5, 1, 4, 3, 2, 1)

my @unique = uniq @duplicates;
say @unique.perl;               #, 2, 5, 4, 3)

This works on strings as well:

use v6;

my @chars = <b c a d b a a a b>;
say @chars.perl;        #"b", "c", "a", "d", "b", "a", "a", "a", "b")

my @singles = uniq @chars;
say @singles.perl;      #"b", "c", "a", "d")

Perl 6 Comments

A few comments to people new to Perl 6:

One should start every Perl 6 script by asking for v6; version 6 of Perl. It is important in order to avoid strange error messages when you happen to run it with perl 5.

You can add .perl to every kind of variable and get back a dumped representation of the data in it. Very handy for debugging.

say() is a built-in function in Perl 6 and it behaves as say() in Perl 5.10, printing to the screen and adding a newline at the end.

Angle brackets < > allow one to create a list of values from a space separated list of items. In Perl 5 the qw() operator was used for this.

Method calls

Actually uniq can also be used as a method call on the array object...

use v6;

my @chars = <b c a d b a a a b>;

my @singles = @chars.uniq;

say @singles.perl;    #"b", "c", "a", "d")

... and some people will prefer to add the .say method call at the end of the expression:


though I think this isn't as clear as having the say at the beginning.

How to get Perl 6 ?

The developers keep an entry with up to date instructions on how to get Rakudo.

The Perl 6 Tricks and Treats newsletter has been around for a while. If you are interested to get special notification when there is new content on this site, it is the best way to keep track:
Full name:
This is a newsletter temporarily running on my personal site ( using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2012-07-04


In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.