Workshop

 <  Day Day Up  >  

If you've started to figure out the pattern to regular expressions, try this quiz to see what you've learned.

Quiz

1:

If you have lines formatted "x=y" , what expression would swap the left and right sides of the expression?

  1. s/(.+)=(.+)/$2=$1/;

  2. s/(*)=(*)/$2=$1/;

  3. s/(.*)=(.*)/$2$1/;

2:

After this code, what's the value in $2 ?

 $foo="Star Wars: The Phantom Menace"; $foo=~/star\s((Wars): The Phantom Menace)/; 

  1. $2 is not set after the pattern match because the match fails.

  2. Wars

  3. Wars: The Phantom Menace

3:

What does the pattern m/^[-+]?[0-9]+(\.[0-9]*)?$/ match?

  1. Dates in the format 04-03-1969

  2. Well- formed numbers such as 45, 15.3, -0.61

  3. Addition-looking patterns: 4+12 or 89+2

Answers

A1:

a. Choice c doesn't include the = symbol in the replacement string and it wasn't captured in $1 or $2 because the = occurred outside of the parentheses. Choice b is invalid; a character must appear in front of the * 's. Choice a does the job nicely .

A2:

a. The match fails because star is not capitalized, and the match doesn't have the non “case-sensitive modifier i . For this reason, you should always test whether the match succeeds before using the values $1 , $2 , and so on. (If the pattern match had used the i modifier or star had been capitalized, choice b would have been the correct response.)

A3:

b. The pattern reads, at the beginning of the line match, an optional + or - , followed by one or more digits, followed ( optionally ) by a decimal and possibly more digits at the end of the line. The pattern matches simple, well-formed numbers.

Activities

  • See whether you can produce a pattern to match a standard time format. All the following should be acceptable: 12:00am , 5:00pm , 8:30AM . These should probably not be accepted: 3:00 , 2:60am , 99:00am , 3:0pm .

  • Write a short program that does the following:

    1. Opens a file

    2. Reads all the lines into an array

    3. Extracts all the words from each line

    4. Finds all words that have at least four consecutive consonants, or nonvowels (such as the words "thou ghts " or "ya rdst ick")

 <  Day Day Up  >  


SAMS Teach Yourself Perl in 24 Hours
Sams Teach Yourself Perl in 24 Hours (3rd Edition)
ISBN: 0672327937
EAN: 2147483647
Year: 2005
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net