Removing redundant array elements

I have an array containing many host names. I want to remove redundant elements of this array, for example:

  • If duplicate entries exist, one of them is deleted.
  • If present, both www.example.com, and example.comis www.example.comremoved.

Removing duplicates already answers here , but how do I get the second condition?

EDIT: To clarify, I have to mention that www.may not be the only present - it can also be abc.def.ghi.foo.bar.baz.qux, and foo.bar.baz.qux, in this case the first is removed.

+4
source share
2 answers

, , , . , . , . , .

my @array = qw(foo.com bar.net www.example.com example.com
            abc.def.ghi.foo.bar.baz.qux foo.bar.baz.qux);
my @result = do {
    my $p;
    map scalar reverse, grep {
        my $x = !defined $p || !m/^\Q$p/;
        if($x) {
            $p = $_;
            $p .= '.' unless m/\.$/;
        }
        $x
    } sort map scalar reverse, @array;
};

use 5.10.0;
say for @result;
+4

, foreach - %seen .

#1 : , $k hostaname, , www., : ( $k) www..

#2 $k (, http:// ..)

#!/usr/bin/perl -w

use warnings;
use strict;

my @hostnames = qw(foo.com bar.net www.example.com example.com);
my %seen = ();
my @result = ();

foreach my $k (@hostnames) {
    $k = "www." . $k if not $k =~ /^www\./; #1
    ... #2
    if (not $seen{$k}) {
        push @result, $k;
        $seen{$k} = 1;
    }
}

- www. :

www.foo.com
www.bar.net
www.example.com
0

All Articles