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

Hi Monks,

Currently I am trying to get the length of the multidimensional array based on some index position. The values are Boolean. I want to count the index (x,2) value equals to ‘1’.

I got the answer for the below code. Please suggest any other smart way to get this?

Thanks
@select = ( ['AAA','A Description',1,0], ['BBB','B Description',0,0], ['CCC','C Description',0,0], ['DDD','D Description',1,0], ['EEE','E Description',1,0], ); for (my $i=0; $i<@select; $i++) { $length++ if($select[$i][2]); } print "\nSelective Length : ", $length; =output 3 =cut
  • Comment on Length of multidimensional array based on the particular index value
  • Download Code

Replies are listed 'Best First'.
Re: Length of multidimensional array based on the particular index value
by davido (Cardinal) on Feb 24, 2011 at 10:07 UTC

    grep in scalar context... evil? It works.

    say scalar grep{ $_->[2] } @select;

    There's also 'for'

    my $length; $length++ if $_->[2] for @select; say $length;

    Dave

      $length++ if $_->[2] for @select;

      Unfortunately, Perl doesn't understand this "double modifier" syntax (syntax error at..., near "] for "), so it would have to be:

      do { $length++ if $_->[2] } for @select;
        it would have to be: do { $length++ if $_->[2] } for @select;

        Can also be:

        $_->[2] and $length++ for @select;

        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.

        there you go taking all my fun away!

        Here's an awful contortion:

        $_->[2]?length++:0 for @select;

        Dave

Re: Length of multidimensional array based on the particular index value
by jwkrahn (Abbot) on Feb 24, 2011 at 10:15 UTC
    $ perl -le' my @select = ( [ "AAA", "A Description", 1, 0 ], [ "BBB", "B Description", 0, 0 ], [ "CCC", "C Description", 0, 0 ], [ "DDD", "D Description", 1, 0 ], [ "EEE", "E Description", 1, 0 ], ); my $length = grep $select[ $_ ][ 2 ], 0 .. $#select; print "Selective Length : $length"; ' Selective Length : 3
Re: Length of multidimensional array based on the particular index value
by k_manimuthu (Monk) on Feb 24, 2011 at 10:50 UTC

    Hi all, Thanks a lot for your valuable suggestion. Here I learned some new things.

    Thanks