1

I have a perl array like below and I have to extract the unique elements of this array. Is there an easy way to do this ?

Perl> print(Dumper(@uncurled_data))
$VAR1 = '100 200';
$VAR2 = '100 200';
$VAR3 = '300 400';
$VAR4 = '100 200';
$VAR5 = '100 200';
$VAR6 = '300 400';
$VAR7 = '300 400';
$VAR8 = '300 400';

When I do this, keys { map { (split /\ /, $_)[0] => 1 } @uncurled_data }, I'll have to do it twice ie, once for each element in the array. Is there any one/liner or simple way to do this ?

Desired output array with 4 elements 100, 200, 300, 400

2 Answers 2

3

First create a list of what you want to make unique,

map { split } @uncurled_data

Then use the standard ways of finding the unique items.

use List::Util qw( uniq );
my @uniq = uniq map { split } @uncurled_data;

or

my %seen;
my @uniq = grep { !$seen{$_}++ } map { split } @uncurled_data;
Sign up to request clarification or add additional context in comments.

1 Comment

Required output array with 4 elements 100, 200, 300, 400
0

You can also do it this way:

my @uniq = sort keys %{+{map {$_ => 1;} map { split } @uncurled_data}};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.