开发者

checking if string contains a character

I am trying to perform a simple check to see if a string contains a "%" but whenever I execute my code it will evaluate the if statement as false no matter what is in the string. My code looks like this:

if ($end_time =~ m{%%}) {
    ($percentage) = $end_time =~ m/=([^%%]*)%%/g;
    $percentage = sprintf("%s%%", $percentage);
    $end_time = "";
}
elsif ($duration =~ m/(overdue)/) {
    $percentage = "$end_time $duration";
    $end_time = "";
}
else {
    $percentage = "100%";
}

and the expected values of $end_time, substitute whatever numeric values you like.

"5%" or "==30%" or "+3m:26s overdue" or "13:48:40"

So if $end_time contains "overdue" or a "%" percentage will be 100% and $end_time will be whatever was in there before the check. And I do understand why I'm getting the results开发者_StackOverflow I'm getting, just not the reason my if statements are always evaluating as false.


String literals and regex literals escape with \, not by doubling, and % does not need to be escaped in either.

if ($end_time =~ m{%}) {
    ($percentage) = $end_time =~ m/=([^%]*)%/g;
    $percentage = sprintf("%s%%", $percentage);
    $end_time = "";

sprintf takes a string with doubled % to indicate %, but that's not related to building strings and regex patterns.


You can also check if "%" is inside your string using string functions such as index()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜