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

Hello I have a simple question. If I am comparing a string with decimals in it, such as 5.1, 5.1.1, 5.2, using if statement, my program currently is only reading 5.1 if I am searching for 5.1.1, what am I doing wrong? if (x == 5.1) { print "x";} elsif (x == 5.1.1) { print "x2";} ect.......

Replies are listed 'Best First'.
Re: if elsif else question
by kyle (Abbot) on Jun 02, 2008 at 18:26 UTC
Re: if elsif else question
by sub_chick (Hermit) on Jun 02, 2008 at 19:01 UTC
    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)"
      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 "."?

      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

Re: if elsif else question
by smokemachine (Hermit) on Jun 03, 2008 at 17:23 UTC
    If are you using perl5.10 you can use ~~...