Perl Lists: Utilizing List::Util - Making First a Little More Complicated
(Page 3 of 5 )
Here is some code that showcases some of the ways you can modify the parameters of the first{Block}List subroutine:
#!/usr/bin/perl
use List::Util qw(first);
@Nums=(1,2,3,4);
$Front = first {$_<5 && $_>3} @Nums;
$Examp = first {$_} @Nums;
$ExampTwo = first {$_>2} @Nums;
$ExampThree = first {$_>1 and $_<2 or $_>1 && $_<3} @Nums;
print $Front . " ";
print $Examp . " ";
print $ExampTwo . " ";
print $ExampThree . " ";
This results in:
4 1 3 2
We can use conditional statements with our subroutine as well:
#!/usr/bin/perl
use List::Util qw(first);
@Nums=(1,2,3,4);
$Front=first{$_} @Nums;
if($Front==1) {print "The value equals 1!"};
$Diff=first{$_>3} @Nums;
if($Diff==1) {print "The value equals 1!"}
else {print "The value is equal to $Diff!"};
This code returns: The value equals 1! The value is equal to 4!
And lastly, we can also use a sequential operator to assign the value to the array and use a conditional to extract a number from it:
#!/usr/bin/perl
use List::Util qw(first);
@Nums=(1..50);
$Front=first{$_>24} @Nums;
print $Front;
This will result in:
25
Next: Max()ing It Out >>
More Perl Articles
More By James Payne