Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How can I select just one time a item from a text file that appear many times and also print the items that are unique
Here is my text file example:
user1*house user2*nothing user3*house user4*house user5*other user6*nothing user7*main

That should print:
house other nothing main

Thank you for the help!!!!

Replies are listed 'Best First'.
Re: Specifics Items in a Text File
by The Mad Hatter (Priest) on May 22, 2003 at 20:06 UTC
    • When you want something unique, use a hash with the things you want to be unique as the keys.
    • When you have text that is seperated by something into fields, use split
    • #!/usr/bin/perl use strict; use warnings; my %uniq = (); while (<DATA>) { chomp; my ($foo, $bar) = split /\*/; $uniq{$bar} = $foo; } print "$_\n" foreach (keys %uniq); __DATA__ user1*house user2*nothing user3*house user4*house user5*other user6*nothing user7*main
Re: Specifics Items in a Text File
by artist (Parson) on May 22, 2003 at 20:04 UTC
    Hi,
    This should help. The order of the output is different however. It preserves the order in which the item is mentioned first time.
    while(<DATA>){ my ($item) = $1 if /user(?:\d+)\*(.*?)$/; next if $seen{$item}; print $item,"\n"; $seen{$item}++; }

    artist

Re: Specifics Items in a Text File
by sauoq (Abbot) on May 22, 2003 at 20:57 UTC

    If this is a one time thing, a oneliner might suffice:

    perl -F'\*' -lane '$h{$F[1]}++;}{print for keys %h' yourfile.txt

    But please be aware of the security implications when using the -n switch.

    -sauoq
    "My two cents aren't worth a dime.";
    
      This oneliner

      perl -lne 's/.*\*//;print unless $f{$_}++' yourfile.txt

      does the same but also maintains the order.

      --

      flounder