in reply to Understanding how sort uniq works

Is it possible to achieve same logic with less lines or nicer solution?

Nicer is in the eye of the beholder. However, here's an SSCCE:

use strict; use warnings; use Test::More tests => 2; use List::MoreUtils 'uniq'; my $v = 'ovedpo15'; my $href = { $v => [5, 3, 2] }; pushsortuniq ($href->{$v}, 3); is_deeply ($href->{$v}, [2, 3, 5], 'Duplicate added, sorted'); pushsortuniq ($href->{$v}, 4); is_deeply ($href->{$v}, [2, 3, 4, 5], 'Non-duplicate added, sorted'); sub pushsortuniq { my ($aref, @topush) = @_; push @$aref, @topush; @$aref = sort (uniq(@$aref)); }

Replies are listed 'Best First'.
Re^2: Understanding how sort uniq works
by AnomalousMonk (Archbishop) on Jul 26, 2019 at 13:37 UTC

    Why not just

    sub sortuniq { my $aref = shift @_; @$aref = sort(uniq(@$aref, @_)); }
    c:\@Work\Perl\monks>perl -wMstrict -le "use Test::More tests => 2; use List::MoreUtils 'uniq'; ;; my $v = 'ovedpo15'; my $href = { $v => [5, 3, 2] }; ;; sortuniq ($href->{$v}, 3); is_deeply ($href->{$v}, [2, 3, 5], 'Duplicate added, sorted'); sortuniq ($href->{$v}, 4); is_deeply ($href->{$v}, [2, 3, 4, 5], 'Non-duplicate added, sorted'); ;; sub sortuniq { my $aref = shift @_; @$aref = sort(uniq(@$aref, @_)); } " 1..2 ok 1 - Duplicate added, sorted ok 2 - Non-duplicate added, sorted

    Update: You can shorten that further to
        sub sortuniq { @{$_[0]} = sort(uniq(@{$_[0]}, @_[ 1 .. $#_ ])); }
    but that just makes things a bit more messy IMHO.


    Give a man a fish:  <%-{-{-{-<