tailieunhanh - Beginning Perl Third Edition PHẦN 5

mà xảy ra được 3. Chúng tôi thiết lập các Iterator để mỗi số lần lượt. Iterator đâu? Kể từ khi chúng tôi đã không cung cấp cho một, Perl sẽ sử dụng $ _. Bây giờ chúng ta làm các khối bốn lần, một lần khi $ _ là 0, một lần khi nó là 1, và như vậy. print "Làm thế nào nhiều $ | CHAPTER 7 REGULAR EXPRESSIONS same since Perl regexes are an extension of egrep s regexes . So why aren t they just called search patterns or something less obscure The actual phrase itself originates from the mid-fifties when a mathematician named Stephen Kleene developed a notation for manipulating regular sets. Perl s regular expressions have grown far beyond the original notation and have significantly extended the original system but some of Kleene s notation remains and the name has stuck. Patterns History lesson aside regular expressions are all about identifying patterns in text. So what constitutes a pattern And how do you compare it against something The simplest pattern is a word a simple sequence of characters and we may for example want to ask Perl whether a certain string contains that word. We can split the string into separate words and then test to see if each word is the one we re looking for. Here s how we might do that usr bin perl use warnings use strict my found 0 _ Nobody wants to hurt you. cept I do hurt people sometimes Case. my sought people foreach my word split if word eq sought found 1 last if found print Hooray Found the word people n Sure enough the program returns success . . . perl Hooray Found the word people But oh that s messy It s complicated and it s slow to boot Worse still the split function which breaks up each line into a list of words actually keeps all the punctuation. We ll see more about split later in the chapter. So the string you wouldn t be found in the preceding example but you . . . would. This is looking like a hard problem but it should be easy. Perl was designed to make easy things easy and hard things possible so there should be a better way to do this. Let s see how it looks using a regular expression usr bin perl use warnings use strict _ Nobody wants to hurt you. cept I do hurt people sometimes Case. 154 CHAPTER 7 REGULAR EXPRESSIONS if _ people print Hooray Found the word .