r_mehmed has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I'm a real newbie,so this might be an easy task to most of you to tackle. I'm trying to pattern macth the date,any date, in a text and then add 'st','nd','rd','th' after each day of the month. All attempts to use an array failed, therefore i opted for the 'easier' solution, but i have hit rock yet again. The code simply doesn't seem to iterate through the if..elsif statements, and always adds the 'st'. This is the code i am using:
#!perl<br> use CGI;<br> $query = new CGI;<br> $source = $query->param('input');<br> print $query->header;<br> $source =~ m/(\d{1,2})(\/|\-)(\d{1,2})(\/|\-)(\d{2,4})/g;<br> my $day = $1;<br> if($day == 1,21,31){<br> $day = "$day\st"<br> }elsif($day == 2|22){<br> $day = "$day\nd"<br> }elsif($day == 3|23){<br> $day = "$day\rd"<br> }elsif($day == 4-20|24-30){<br> $day = "$day\th"<br> }<br> print "$day";<br>
Pls help!!!

Added <code> tags - dvergin 2002-11-31

Replies are listed 'Best First'.
Re: pattern matching
by tachyon (Chancellor) on Nov 01, 2002 at 01:03 UTC

    Very close but you can't do it quite that way. Here is your code in working form:

    $source =~ m!(\d{1,2})[-/](\d{1,2})[-/](\d{2,4})!g; my $day = $1; if( $day == 1 or $day == 21 or $day == 31 ){ $day .= 'st'; }elsif( $day == 2 or $day == 22 ){ $day .= 'nd'; }elsif( $day == 3 or $day == 23 ){ $day .= 'rd'; }else { $day .= 'th'; }

    I have shown you the use or character classes and different regex delimiters (you can use ! or anything else for that matter, not just /) as well as the .= operator. A little indenting makes it easier to read. The last case is just an else as we want to catch everything that is not a st/nd/rd with th

    This also works and demonstrates an alternative to the if elseif else structure for simple stuff

    $day .= ( $day == 1 or $day == 21 or $day == 31 ) ? 'st' : ( $day == 2 or $day == 22 ) ? 'nd' : ( $day == 3 or $day == 23 ) ? 'rd' : 'th';

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: pattern matching
by kelan (Deacon) on Nov 02, 2002 at 05:20 UTC

    Here's a Perl6 regex to do the matching.

    ### <Perl6> $source =~ / $day:=(\d<1,2>) <[-/]> (\d<1,2>) <[-/]> (\d<2,4>) /; ### </Perl6>
    After the match, $day will be bound to what was captured in $1, and you can proceed to appending suffixes as mentioned above by tachyon. I much like the method using the ternary operator.

    On a side note, why are you using the /g modifier in your match? I can't see any purpose that it serves.

    kelan


    Perl6 Grammar Student