Extracting-Components-from-a-Unix-Style-Date
4.6.2 Extracting Components from a Unix-Style Date
Now, we present another example that illustrates remembering results of pattern matching. Here, we assume we are on a Unix machine. Using backticks, we call the Unix date command which returns something like the following.
Mon Aug 17 19:17:00 MDT 1998
In this program, we match over a string that contains such a date string. The pattern expression has ten starting parentheses and ten closing parentheses. Therefore, ten variables, $1 through $10 are set. The matched substrings are remembered and stored in the array @fields. In the assignment statements that follow, sometimes we assign from a numbered variable and sometimes from an element of @fields.
Program 4.22
#!/usr/bin/perl $date = `date`; @fields = ($date =~ /^(\w+) ((\w+) (\d+)) ((..):(..):(..)) (\w+) (\d+)/); $day = $1; $monthdate = $2; $month = $3; $date = $4; $time = $5; $hour = $fields[5]; $minutes = $fields[6]; $seconds = $fields[7]; $timeZone = $9; $year = $10; print "Day = $day\nMonth and Day = $monthdate\n"; print "Month = $month\nDate = $date\n"; print "Time = $time\nHour = $hour\n"; print "Minutes = $minutes\nSeconds = $seconds\n"; print "Time Zone = $timeZone\nYear = $year\n";
