in reply to how to convert fractional string to decimal numbers ?

 my $fractionValue = ( $str =~ m{^(\d+)/([1-9]\d*)} ) ? $1/$2 : "undefined"; wow..it seems to work. But i've always got some problem understanding regex.. if you don't mind explaining it to me how it works?

1. =~ = (doesn't this means.."not equal to"?)
2. m{ } = (no idea)
3. $1/$2 = (I never knew you could do things like that after a one line condition? What does it actually do?)

Replies are listed 'Best First'.
Re^2: how to convert fractional string to decimal numbers ?
by graff (Chancellor) on Dec 17, 2008 at 07:29 UTC
    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 "!=".

Re^2: how to convert fractional string to decimal numbers ?
by ikegami (Patriarch) on Dec 17, 2008 at 07:08 UTC

    m{...} is the match operator, often seen as /.../. See perlop and perlre

    =~ tell m//, s/// and tr/// on which variable to operate.

    $1 and $2 are set by m//. See perlre

    EXPR ? EXPR : EXPR is the conditional operator. See perlop