Learning PERL

Practice 3. Regular Expressions: Matching and Substitution(Transformation)

    A. Patern Matching : Operator "=~/ /"
    A-1) Standard form

    $result = "I love cat and dog." =~/dog/ ;
    if ($result)
    { print "Match ! \n";
    } else {
    print "No Match ! \n";
    }

    A-2) Practical form: using "$_"
    $_ = "I love cat and dog." ;
    if (/dog/)
    { print "Match ! \n";
    } else {
    print "No Match ! \n";
    }

    A-3) Matching Rules
    =~/dog/ : standard
    =~/d.g/ : arb. one letter for "o"
    =~/d?g/ : 0 or 1 time repreat of "d"
    =~/d*g/ : 0 or more of "d" (ex: dg, dddg,..)
    =~/d+g/ : 1 or more of "d"
    ... (See the reference table.)




    B. Substitution: Operator "=~s/ / /"
    B-1) Standard form

    $str = "I like dog." ;
    $result = $str =~ s/dog/cat/ ;


    B-2) Practical form: using "$_"
    $_ = "I like dog." ;
    $result = s/dog/cat/ ;
    <--"$_=~" can be omitted.

    B-3) Substition vs. Transformation: "=~tr/ / /"
    $_ = "I like dog." ;
    $result = tr/abcd/ABCD/ ;
    <--Exchanging ONE BY ONE.