Perl Programming Page 4 - Perl Lists: A Final Look at List::Util |
Shuffle is a pretty simple function. It takes a list and returns it in a random order. That's it. Here it is in code: #!/usr/bin/perl use List::Util qw(shuffle); @nums = shuffle 0..10; print @nums; Here we create a list (@Nums) of random numbers by using shuffle. The numbers range from 1-10 and their order will vary each time you run this program. Here is my first result: 014329685107 Another way of sorting with shuffle is by using a predefined array: #!/usr/bin/perl use List::Util qw(shuffle); @Nums = (1,2,3,4,5,6,7,8); @Weird=shuffle(@Nums); print @Weird; Which once again gives us a randomly shuffled list. My first result was: 25871643 Sum()ming It Up Our final subroutine is sum(), which is used to sum up the numeric values in a list. Here are some samples: #!/usr/bin/perl use List::Util qw(sum); @Nums = (1,2,3,4,5,6,7,8); @Weird=sum(@Nums); print @Weird; Here, the result is: 36 Or 8+7+6+5+4+3+2+1 We can also assign some wacky values using expressions in our list, and then sum up the total: #!/usr/bin/perl use List::Util qw(sum); @Nums = (1+1,2+2,3*3,4*8,5*7,6*6,7+4,8+2); @Weird=sum(@Nums); print @Weird; Here we are given the sum: 139 Lastly, we can find the sum of more than one list by using the following technique: #!/usr/bin/perl use List::Util qw(sum); @Nums = (1+1,2+2,3*3,4*8,5*7,6*6,7+4,8+2); @Nums2= (1,2,3,4,5,6,7,8); @Weird=sum(@Nums,@Nums2); print @Weird; This takes the two arrays, adds them together, and gives us the sum: 175 Conclusion And so we come to the end of our discussion of the List::Util subroutines. In our next tutorial, we will finally discuss the long anticipated Hashes, and perhaps, if not in the next article then the one after that, the Multidimensional list. There's a lot to cover, so be sure to drop by often. Till then...
blog comments powered by Disqus |
|
|
|
|
|
|
|