1: #!/usr/bin/perl -w
   2: #
   3: # Three map one-liners for dealing with lists
   4: 
   5: # Removing duplicates
   6: 
   7: my @list1 = ('a', 'b', 'c', 'b', 'a', 'b', 'd', 'e');
   8: my @list2 = ('x', 'y', 'y', 'z');
   9: my @dedupedlist = keys %{{ map { $_ => 1 } (@list1, @list2) }};
  10: print "@dedupedlist\n";
  11: 
  12: ###################################
  13: 
  14: # Determining whether an item is in a list
  15: 
  16: my $item = 'aaa';
  17: my @list = ('aaa', 'bbb', 'ccc', 'ddd', 'eee');
  18: 
  19: if ({ map { $_ => 1 } @list }->{$item})
  20: {
  21:     print "Yes!\n";
  22: }
  23: else
  24: {
  25:     print "No!\n";
  26: }
  27: 
  28: ###################################
  29: 
  30: # (The finale...)
  31: # 'Diff' two lists
  32: 
  33: my @lista = ('R', 'o', 'b', 'e', 'r', 't');
  34: my @listb = ('e', 'r', 't');
  35: my @difflist =  map {  {map { $_ => 1 } @listb}->{$_} ? ()  : $_  } @lista;
  36: print "@difflist\n";
  37: 

Replies are listed 'Best First'.
Re: Three map one-liners for lists
by merlyn (Sage) on Apr 19, 2001 at 20:32 UTC
    Interesting as an exercise, but all three of these are slower (and I'd also suggest harder to understand and maintain) than the other forms published in the perlfaq.

    -- Randal L. Schwartz, Perl hacker

      Thanks - I should have checked the faq first!