in reply to Calculated % of data greater than $x in an array
If all you're interested in is a short way (without having to type in the lines of a loop structure), then the following is a way to do it (there may be shorter ways):
#!/usr/bin/perl use strict; use warnings; my $y= 10; my @array =(1, 4, 5, 7, 8, 9, 10, 20, 30, 40, 60); my $greater = 50 ; my $num = scalar(@array); my $percent = (scalar(grep{$_ > $greater} @array)/$num)*100; print "Percent of \@array's $num items greater than $greater is $perce +nt%\n"; exit(0);
Of course you can shorten it even more by putting the scalar(@array) directly in the division in plac of the $num that I use. I did it that way so that I could report the number of elemnts in the array in the print statement.
But overall I completely agree with ikegami in as much as several folks of late have asked how to things 'without looping' but that reqire 'looping' to accomplish. The answer, in general, is that 'you can't'. So I have been interpreting the questions to mean either (1) 'how do I do it without having to type in the loop structures' and/or (2) 'Is there a way that perhaps the compiler (interpreter) can do it for me more efficiently'.
I don't knowwhat the OP was looking for, but hopefully we answered the question. Good luck,
|
|---|