in reply to if elsif else question

You could use regexes but I don't know for sure what your strings consist of:
my $x = '5.1'; my $y = '5.1.1'; if($x =~ /5.1/) { print "X equals 5.1 \n"; } if($y =~ /5.1.1/) { print "Y equals 5.1.1 \n"; }
Hope this helps.


Es gibt mehr im Leben als Bücher, weißt du. Aber nicht viel mehr. - (Die Smiths)"

Replies are listed 'Best First'.
Re^2: if elsif else question
by FunkyMonk (Bishop) on Jun 02, 2008 at 19:34 UTC
    There are several things wrong with /5.1/
    • "." inside a regex is special - it matches any character except "\n".
    • the regex will match any string that contains the sequence 5, "any char except \n", 1. ie it will match (for example) "501", "5:1", "I have 5.1 experience points"
    The solution is to anchor the regex at the start and end of the string, and to escape ".": /^5\.1$/

    eq is a far better operator when you want to test if two strings are equal!

    See perlretut for a regexp tutorial and perlre for the full monty on regular expressions.


    Unless I state otherwise, all my code runs with strict and warnings
      My mistake on forgetting to add the escape char:  '\' before '.' :)
      Thanks.


      Es gibt mehr im Leben als Bücher, weißt du. Aber nicht viel mehr. - (Die Smiths)"

      oops, how did I miss that special regex meaning of "."?

Re^2: if elsif else question
by linuxer (Curate) on Jun 02, 2008 at 19:24 UTC

    But you should use anchors in your regex, otherwise it might match, where you don't want it to match

    my $x = '5.1.1'; # OOPS if ( $x =~ m/5.1/ ) { print "'$x' is 5.1\n"; } # better if ( $x =~ m/^5.1$/ ) { print "'$x' is 5.1\n"; }

    update: please read on at FunkyMonks post