Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Unique values using grep

Of course there is an even shorter way to write it:

#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';

my @data = qw(Earth Mars Earth Venus Earth Mars);

#my %seen;
#my @unique = grep { !$seen{$_}++ } @data;

my @unique = do { my %seen; grep { !$seen{$_}++ } @data };

print "@unique\n"; # Earth Mars Venus

In this version you can even assign the values back to the original array writing:

@data = grep { !$seen{$_}++} @data;