Chapter 10

sort, map, and grep

WHAT YOU WILL LEARN IN THIS CHAPTER:

  • Sorting lists alphabetically and numerically
  • Creating custom sorts with sort subroutines
  • Using map and grep to efficiently transform and filter lists and avoiding their traps
  • Combing map, sort, and grep to create powerful list manipulations

WROX.COM CODE DOWNLOAD FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at http://www.wrox.com/remtitle.cgi?isbn=1118013847 on the Download Code tab. The code for this chapter is divided into the following major examples:

  • example_10_1_soldier.pl
  • example_10_2_is_prime.pl
  • example_10_3_celsius.pl
  • listing_10_1_employee.pl
  • listing_10_2_collate.pl
  • listing_10_3_locale_sort.pl

By this time in the book you should have a sufficient understanding of Perl that you’re able to use it for small tasks in relation to your day-to-day work. However, there’s an odd sort of “litmus test” for Perl developers. For some reason, understanding sort, map, and grep seems to be the difference between beginner and intermediate Perl developers. When you cross this threshold, you’re well on your way to being a Perl expert.

Though sort, map, and grep have been mentioned briefly, their usage has deliberately been kept simple. Now you can see a bit more about their full power.

The one thing to remember is that each of these creates a new list from an old list.

BASIC SORTING

The sort builtin sorts a list and returns a new list. It has three forms:

sort LIST sort BLOCK LIST sort SUBNAME ...

Get Beginning Perl now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.