in reply to Re: How can I make a string unique (quicker than my approach at least)
in thread How can I make a string unique (quicker than my approach at least)

I use that snippet sometimes since some older version of List::Util do not include a uniq function.

The code means:

sub uniq { my %h; # Keep track of things seen. grep { # 4: Return items seen only once. not $h{$_}++ # 2: Item is not (yet) be seen. # 3: ++ would then say item was seen. } @_; # 1: For each input... }
  • Comment on Re^2: How can I make a string unique (quicker than my approach at least)
  • Download Code

Replies are listed 'Best First'.
Re^3: How can I make a string unique (quicker than my approach at least)
by Timka (Acolyte) on Apr 03, 2024 at 04:38 UTC

    Input:

    cat in ID1 nick-john-helena ID2 george-andreas-lisa-anna-matthew-andreas-lisa ID3 olivia-niels-peter-lars-niels-lars-olivia-olivia

    Code:

    perl -MList::Util=uniq -ple ' s/ ^ # Beginning of line (BOL). \w+ # Any "words". \s+ # Any whitespace (like tabs). \K # "Keep" whats to the left. (\S+) # Capture and replace next non whitespace (words). / join "-", # 4: n1-n2-n3 uniq # 3: [ "n1", "n2", "n3" ] split "-", # 2: [ "n1", "n2", "n1", "n3" ] $1 # 1: n1-n2-n1-n3 /xe # Freespace regex and eval replacement. ' in

    Output:

    ID1 nick-john-helena ID2 george-andreas-lisa-anna-matthew ID3 olivia-niels-peter-lars