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

I want an if statement that will be true if my string is equal to any three letter string that begins with 'R'. If ($string eq "R**") { #blar } Something like that. How do I do this?

Replies are listed 'Best First'.
Re: Wildcard?
by broquaint (Abbot) on May 30, 2002 at 12:41 UTC
    You could use character classes in your regex
    if($string =~ /^R[a-zA-Z]{2}\z/) { ... }
    So that will match 'Rat', 'Rod' and 'Ran' but not 'R4t', 'R0d' or 'RA\n'. For more info on regular expressions see the perlre manpage.
    HTH

    _________
    broquaint

Re: Wildcard?
by Hofmator (Curate) on May 30, 2002 at 13:01 UTC
    In your special case you can do without a regex and instead use substr and length:
    while (<DATA>) { chomp; print if substr($_,0,1) eq 'R' && length == 3; } __DATA__ raa Raa Raab

    Update: Rereading your question, my solution only applies if you read 'letter' as 'any character'.

    -- Hofmator

Re: Wildcard?
by Molt (Chaplain) on May 30, 2002 at 12:33 UTC

    Simple regexp.. if ($string=~ /^R..$/i) { #bleah }. The i at the end makes it case-insensitive, if you want it case sensitive (ie. matches 'Ray' but not 'ray') then remove it.

    Update: Thanks Juerd for the correction below, although realised we're both wrong!

    The following will match any three letter string, starting with a 'r' and optionally ending with a newline... if ($string =~ /^R[A-Z][A-Z]\n?$/i) { # bLEEEA }

    Again this is case insensitive, to make it sensitive now though you need to change the A-Z bits into which case you want.

      /^R..$/

      That will match ray but also ray\n, but not ra\n.

      /^R..\z/s
      \z is end of string, /s makes . match \n.

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

        If you've got the /s switch on though this'll happily match R\n\n\n, won't it?

        Update: Oops, did wrong number of \n's. R\n\n does seem to pass this match, unless the code below is wrong..

        #!/usr/bin/perl -w use strict; my @tests = ( "R\n\n", # Passes "Roo", # Passes "roo", # Fails "Roo\n", # Fails ); foreach (@tests) { if (/^R..\z$/s) { print "$_ passes\n"; } else { print "$_ fails\n"; } }