I like
Grandfather's solution. It uses the scalar value of grep in an "if" statement and the simplicity of this is normally the best way to go. If @array is very big, here is one way to stop processing once you have a "match". This speeds things up at the cost of complexity.
#!usr/bin/perl -w
use strict;
my @array=(34,52,67,3,66);
is_value_gt_min_array_element(5,\@array) ?
print "yes, 5 is greater than @array\n"
: print "no, 5 isn't greater than: @array\n";
is_value_gt_min_array_element(3,\@array) ?
print "yes, 3 is greater than @array\n"
: print "no, 3 isn't greater than: @array\n";
is_value_gt_min_array_element(2,\@array) ?
print "yes, 2 is greater than @array\n"
: print "no, 2 isn't greater than: @array\n";
sub is_value_gt_min_array_element
{
my ($value, $arrayref) = @_;
foreach (@$arrayref)
{
return 1 if ($value > $_); #this is a "found it!"
#stop searching for another one
}
return 0;
}
print "There are ", scalar(grep{$_>3}@array), " numbers ",
"greater than 3 in: @array\n";
__END__
prints:
yes, 5 is greater than 34 52 67 3 66
no, 3 isn't greater than: 34 52 67 3 66
no, 2 isn't greater than: 34 52 67 3 66
There are 4 numbers greater than 3 in: 34 52 67 3 66
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.