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

It's late and I can't get this to work for some reason.

I have two variables: $city and $cityState

$city = "Chicago"; $cityState = "Chicago, IL";
You can see that the $city variable is just a city name and the $cityState variable is the City with a comma and then the state.

How can I get this code to check to see if the Cities match?

The below code shouldn't match.
#!/usr/bin/perl my $city = "Naperville"; my $cityState = "Chicago, IL"; if ( $cityState =~ /\$city+/) { print "They match!"; } else { print "dont match"; }

The below code should match.
#!/usr/bin/perl my $city = "Chicago"; my $cityState = "Chicago, IL"; if ( $cityState =~ /\$city+/) { print "They match!"; } else { print "dont match"; }

Replies are listed 'Best First'.
Re: Matching Part of a String in a IF Statment
by Corion (Patriarch) on Dec 12, 2005 at 08:53 UTC

    You're quoting the dollar sign of $city when you want $city to be interpolated. Perl knows when dollar is meant to mean "end-of-string" and when it's meant to mean "begin of a scalar variable". You want the following:

    #!/usr/bin/perl my $city = "Naperville"; my $cityState = "Chicago, IL"; if ( $cityState =~ /\b\Q$city\E\b/) { print "They match!"; } else { print "dont match"; }

    I've added \Q..\E modifiers, so you can have cities with "special" characters in their names, like []+*^ - I don't know if that's the case with your data but it's better to be safe than sorry. I also added word boundaries so Naper and Naperville are treated as two distinct towns.

Re: Matching Part of a String in a IF Statment
by murugu (Curate) on Dec 12, 2005 at 09:06 UTC
    Hi awohld,

    Its not matching because, it's trying to match '$city' i.e $city doesn't get interpolated.

    Remove that \ before $city, then it will match. You should also add boundary condition \b to the expression so that the you can do exact string match. (i.e)substring matches can be avoided

    Regards,
    Murugesan Kandasamy
    use perl for(;;);

      Technically it's trying to match $cit followed by one or more of y</pedant>