Perl Programming Page 2 - Perl Lists: A Final Look at List::Util |
Min(List) is very similar to max(List) in its usage. The only difference is that it returns the minimum numeric value in a list. Here we have it in code: #!/usr/bin/perl use List::Util qw(min); @Nums=(1,900,50,22); $Low=min(@Nums); print $Low; Here, we create a list named '@Nums', in which we store several numeric values. Next, we use min() to scan the list and find the lowest value, and store it in the $Low variable. Finally, we print the value out, resulting in: 1 As with our other subroutines, we can use min() in conjunction with operators, statements, and the like. Here it is with an if...else statement: #!/usr/bin/perl use List::Util qw(min); @Nums=(1,900,50,22); $Low=min(@Nums); if($Low > 2) {print "The number $Low is greater than 2!"} else {print "The value $Low is less than 2!"}; Again, we call our subroutine, then create the @Nums list, filling it with values. We then use min() to parse out the lowest value and store it in $Low. Lastly, we create an if...else statement that says if the value of $Low is greater than two, print out a statement. If the value is less than two, print out another statement. You will note of course that if the value were two, nothing would have happened. Here is the result: The value 1 is less than 2! We can perform some mathematics on our subroutine as well: #!/usr/bin/perl use List::Util qw(min); @Nums=(1,900,50,22); $Low=min(@Nums) + 1 * 25 +6 /9 -2; print $Low; Here we take the value of $Low and beat it to death with a bunch of math that I randomly selected, yet which oddly enough put us almost back at the number 25: 24.66666666666667 Give or take a six... Finally, here is how we can compare the lowest values from two separate lists and have something occur from the result: #!/usr/bin/perl use List::Util qw(min); @Nums=(1,900,50,22); @Nums2=(90..898); $Low=min(@Nums); $Low2=min(@Nums2); if($Low > $Low2) {print "$Low is greater than $Low2"} else {print "$Low is less than $Low2"}; print "\n" .$Low . "\n"; print $Low2; Here, this code creates two lists, @Nums and @Nums2. It assigns the first list some numeric values, and then uses a sequential operator to add the values 90-898 to @Nums2. Next, it uses min() to extract the lowest numeric value from @Nums and assign it to $Low. It then uses min() again to assign the lowest numeric value in @Nums2 to the variable $Low2. Finally, it runs an if...else statement that states if $Low is greater than $Low2, print something. Otherwise it will print something else. Note that if $Low and $Low2 are equal, nothing will happen. Here is the result: 1 is less than 90 1 90
blog comments powered by Disqus |
|
|
|
|
|
|
|