Zesa Rex Zesa Rex - 2 months ago 6
Perl Question

In Perl, is there an operator to check a string roughly for another string?

I guess this is a quite simple question but after 20 minutes of googling I couldn't find anything to solve my problem.

So I want to check a string variable whether it has

'OK'
somewhere in it or not.

I tried using
~
and
~~
.
~
is giving me an error and
~~
is says not the right operator is guess. I thought of
~
as something like "roughly" but it seems like that's not true. Here is my code:

open (INPUT, "<", $curfile);
while (<INPUT>) {
$firsttenchars= substr ($_, 0, 10);
if ($firsttenchars ~ "OK")
{
print "success";
}
}
close INPUT;

Answer

You are looking for a pattern match.

if ($firsttenchars =~ m/OK/) { ... }

This will return true if the literal string 'OK' (case-sensitive) is found somewhere inside of $firsttenchars. It doesn't care how often, and once it finds it, it stops looking.

The stuff inside the // is a regular expression, short regex. Those are used to creae patterns. =~ is the binding operator that binds a scalar value ($firsttenchars) to a pattern match. The m of the m// is the match operator. There is also an s/// that is used to replace something by a pattern.

You can read perlrequick, perlre and perlretut for more information. The regex tag wiki here on Stack Overflow is an awesome resource to get started with regular expressions.


The ~ operator is the bitwise negation operator.

Unary "~" performs bitwise negation, that is, 1's complement. For example, 0666 & ~027 is 0640. (See also Integer Arithmetic and Bitwise String Operators.) Note that the width of the result is platform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64 bits wide on a 64-bit platform, so if you are expecting a certain bit width, remember to use the "&" operator to mask off the excess bits.

The ~~ operator is called smart match. It's been there for a while in Perl and it supposed to do smart things. It behaves differently based on what you've got on the RHS (right-hand side) and LHS (left-hand side). It's still considered experimental and many people in the Perl community find it controversial. You used it with two scalars, both of them containing strings. That turns it into an eq, which checks for string equality.

Any Any string equality
like: Any eq Any

A complete overview of all operators in Perl can be found in perlop. Note this links to the most recent version (5.24 at the time of writing). Your Perl might be older, and might not have all of them.


A faster way of checking if 'OK' is contained inside of that string is the index built-in. It returns the first occurrence of a string within another string. Because it returns -1 if it doesn't find that string, you need to explicitly check the return value.

if (index($firsttenchars, 'OK') != 0) { ... }

This is a bit more to write than the pattern match, but it's a lot faster.

Comments