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

hai monks,

please can anybody explain me about the meaning of the following code

push(@cn1_new,grep {!$ss{$_}++} @cn1_newnnn);

thanks !!!!!!!! in advance by sanku

hai monks thanks for your replays by sanku.

Replies are listed 'Best First'.
Re: meaning for the code
by GrandFather (Saint) on Dec 23, 2006 at 04:14 UTC

    It pushes the first instance of each different item in @cn1_newnnn into the array @cn1_new and counts the number of repeats in %ss (assuming %ss is empty beforehand). Consider:

    use strict; use warnings; my @cn1_new; my @cn1_newnnn = qw(apple orange grape apple lemon banana apple grape) +; my %ss; push(@cn1_new,grep {!$ss{$_}++} @cn1_newnnn); print "$_: $ss{$_}\n" for sort keys %ss; print "@cn1_new\n";

    Prints:

    apple: 3 banana: 1 grape: 2 lemon: 1 orange: 1 apple orange grape lemon banana

    DWIM is Perl's answer to Gödel

      ++GrandFather.
      Also, if %ss is not used later in the program, then it was probably just used as a 'seen' hash, to keep track of the values seen during the removal of duplicate elements from the array. In the past, the common perl idiom for this has been my %seen; @foo = grep {!$seen{$_}++} @bar;, which looks just like the OP's code. This form 'leaks' the %seen hash, and is *very* confusing to many programmers. To improve clarity and stop the leak, it can be wrapped in a subroutine. The sub is often named 'uniq', the same name as the similar Unix program:

      # Remove duplicate elements, leaving only unique elements. sub uniq { my %seen; return grep { ! $seen{$_}++ } @_; } @foo = uniq @bar;
      Currently, the best practice it to import uniq() from List::MoreUtils, rather than coding it directly:
      use List::MoreUtils qw( uniq ); @foo = uniq @bar;

Re: meaning for the code
by davido (Cardinal) on Dec 23, 2006 at 05:00 UTC

    Note that unless @cn1_new already contains data, push is not needed. You could use simple assignment like this:

    my( @cn1_new ) = grep { !$ss{$_}++ } @cn1_newnnn;

    Dave

Re: meaning for the code
by McDarren (Abbot) on Dec 23, 2006 at 04:04 UTC
    Blah! ..ignore this. See below

    It searches the array @cn1_newnnn for the keys of the hash named $ss. Any keys that are not found, are pushed onto the array @cn1_new.

Re: meaning for the code
by Anonymous Monk on Dec 29, 2006 at 12:26 UTC
    ~ what does this means, how to mention this symbol...