Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

($date=~/(\d\d):(\d\d):(\d\d)/) how this works

Status
Not open for further replies.

kalunina

Instructor
Aug 7, 2005
2
LK
if ($date=~/(\d\d):(\d\d):(\d\d)/){
$hh=$1;
$mm=$2;
$ss=$3;
....
....
}

how this separate date value and put to these variables?.(how they only assign the value )
 
\d matches a character 0-9. If your $date looks like 09:08:05, then
Code:
/\d\d:\d\d:\d\d/
will match it. If you put parentheses around parts of the expression,
Code:
/[red]([/red]\d\d[red])[/red]:[green]([/green]\d\d[green])[/green]:[blue]([/blue]\d\d[blue])[/blue]/
then the parts in the parentheses get allocated to the special variables [red]$1[/red], [green]$2[/green], [blue]$3[/blue]... $n if it matches. If not, then they are set to undefined.

So the regular expression as a whole returns a boolean to indicate if it matches or not. If it matches, then the three pairs of digits get mapped to $1, $2, $3 respectively.

Does this help?
 
You can set the regex up in various ways to perform this task:-

Code:
[b]#!/usr/bin/perl[/b]

@dates = qw( 05:15:06 04:30:07 10:11:17 2:15:00 13:21:15 );

foreach $date (@dates) {

  if ( $date=~[b][red]/(\d\d):(\d\d):(\d\d)/[/red][/b] ) {
    print "$date\tMATCHED\n";
  } else {
    print "$date\tFAILED TO MATCH\n";
  }
    
  if ( $date=~[b][red]/(\d{2}):(\d{2}):(\d{2})/[/red][/b] ) {
    print "$date\tMATCHED\n";
  } else {
    print "$date\tFAILED TO MATCH\n";
  }
  
  if ( $date=~[b][red]/((\d{2}):){2}(\d{2})/[/red][/b] ) {
    print "$date\tMATCHED\n";
  } else {
    print "$date\tFAILED TO MATCH\n";
  }

}

outputs:-
05:15:06 MATCHED
05:15:06 MATCHED
05:15:06 MATCHED

04:30:07 MATCHED
04:30:07 MATCHED
04:30:07 MATCHED

10:11:17 MATCHED
10:11:17 MATCHED
10:11:17 MATCHED

2:15:00 FAILED TO MATCH
2:15:00 FAILED TO MATCH
2:15:00 FAILED TO MATCH

13:21:15 MATCHED
13:21:15 MATCHED
13:21:15 MATCHED


Kind Regards
Duncan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top