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 "!=".
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.