Perl Programming Page 3 - Perl Lists: A Final Look at List::Util |
This subroutine works like min(), only for strings. It will find the smallest valued string in a list, and return it. Here are some examples of its use: #!/usr/bin/perl use List::Util qw(minstr); @Letters=('A','B','C','D'); $Small=minstr(@Letters); print $Small; In the above example, we call the minstr() sub near the top, then create a list, @Letters, and give it some values. Next, we use minstr() to extract the smallest value in the list and store it in our $Small variable. Finally, we print out the result: A As you may recall from our maxstr() examples in the previous article, the values 'A' and 'a' are not equal. Consider this code: #!/usr/bin/perl use List::Util qw(minstr); @Letters=('A','a','B','b','C','c','D','d'); $Small=minstr(@Letters); print $Small; Which value will be the lowest here? If you guessed "A," then you are correct. Always remember that uppercase letters in Perl are worth less than lowercase values. Let's see how they fare against shifted characters: #!/usr/bin/perl use List::Util qw(minstr); @Letters=('A','a','B','b','C','c','D','d','!','@','#','$'); $Small=minstr(@Letters); print $Small; In this example, the smallest result is the exclamation point(!). Next we will look at whole strings and see how they compare: #!/usr/bin/perl use List::Util qw(minstr); @Letters=('Apple','Pie','999','@#$%!'); $Small=minstr(@Letters); print $Small; In this situation, '999' is the smallest value. Finally, let's test a-z, A-Z, 1-100, and some more shift characters to see which one has the least value: #!/usr/bin/perl use List::Util qw(minstr); @Letters=('A'..'Z','a'..'z','1'..'100','!','@','#','$','%','&','+'); $Small=minstr(@Letters); print $Small; Again, our smallest value is the exclamation point(!).
blog comments powered by Disqus |
|
|
|
|
|
|
|