my $fractionValue =
( $str =~ m{^(\d+)/([1-9]\d*)} ) # regex match will evaluate to
+true or false
? # the "ternary operator" -- if above condition is tru
+e, then...
$1/$2 # return this value (using the 1st and 2nd matched
+digit strings
: # otherwise (if above condition was false), ...
"undefined" # return this value
; # end of statement
The "m{...}" is just another form of the regex match operator; note that all the following expressions mean the same thing in perl:
/blah/
m/blah/
m=blah=
m!blah!
m{blah}
When the regex delimiter is "/", the "m" is optional; but any other character can be used as the delimiter, and in that case, the initial "m" is required. The reason for using a character other than "/" as the delimiter on the regex is to avoid the "match-stick syndrome" that happens when you need to match a literal slash character -- given the following two alternatives, I'd rather use the second one:
/http:\/\/my\/path\/to\/insanity/
m{my/path/back/to/sanity}
As for the $1 and $2, these are the "capture" variables set by the regex to contain the strings that were matched within consecutive pairs of parentheses -- another example:
$_ = "123.456/789-0";
if ( /(\d+)\D(\d+)\D(\d+)/ ) {
printf( "Found three numbers: %d was between %d and %d\n", $2, $1,
+ $3 );
}
The value assigned to a capture variable will remain available for use until the next time you do a regex match.
As for "=~" vs. "=", that's a pretty basic perl thing; note that the last example above could have done the match like this:
if ( $_ =~ /(\d+)\D(\d+)\D(\d+)/ ) { ...
The "=~" binds a given variable to the regex match "m//" operator (or the substitution "s///" or character replacement "tr///" operators); this can be done implicitly for the global "default string" variable $_, but must be done explicitly for any other variable (so: $str =~ m/blah/).
The "not equal to" operator in perl (a logical operator, for use in conditionals) is "!=". |