in reply to Re: how to convert fractional string to decimal numbers ?
in thread how to convert fractional string to decimal numbers ?
The "m{...}" is just another form of the regex match operator; note that all the following expressions mean the same thing in perl: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
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:/blah/ m/blah/ m=blah= m!blah! m{blah}
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:/http:\/\/my\/path\/to\/insanity/ m{my/path/back/to/sanity}
The value assigned to a capture variable will remain available for use until the next time you do a regex match.$_ = "123.456/789-0"; if ( /(\d+)\D(\d+)\D(\d+)/ ) { printf( "Found three numbers: %d was between %d and %d\n", $2, $1, + $3 ); }
As for "=~" vs. "=", that's a pretty basic perl thing; note that the last example above could have done the match like this:
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/).if ( $_ =~ /(\d+)\D(\d+)\D(\d+)/ ) { ...
The "not equal to" operator in perl (a logical operator, for use in conditionals) is "!=".
|
|---|