Dima Candu
Dima Candu

Reputation: 25

Perl pattern match and arithmetic operation at the same time

Can i make match pattern and arithmetic operation at the same time ?

   print 5 / 3 !~ /\.\d*/;

result 5 , why ?

 $str = 5 / 3;
 print $str !~ /\.\d*/;

total correct. How can i make in the one expression ?

Upvotes: 1

Views: 239

Answers (3)

Richard Simões
Richard Simões

Reputation: 12791

Default order of operations is giving you the unexpected result. Instead, try:

print +(5 / 3) !~ /\.\d*/;

But, as pointed out by others, that's a terrible way to test whether 3 divides 5. You have the modulus operator for that:

print 5 % 3 == 0;

Upvotes: 5

Hunter McMillen
Hunter McMillen

Reputation: 61515

It is returning 5 because 3 !~ /\.\d*/ returns 1 and 5 / 1 = 5`.

You can wrap your arithmetic expression in parens to have Perl evaluate it first:

print ((5 / 3) !~ /\.\d*/);

Upvotes: 1

user1558455
user1558455

Reputation:

You just need to use brackets!

What happend in your code is basically:

print 5 / (3 !~ /\.\d*/);

So the RegEx comes first, then the / division.

I think you want to do something like:

print ((5 / 3) !~ /\.\d*/);

# or 

my $division = 5 / 3;
print $division if $division !~ /\.\d*/;
# or 
# print (5 / 3) if (5 / 3) !~ /\.\d*/; 
# but the calculation need to be twice here!

If i understand your problem correct, you just want to print if the division does not return a float:

print "test" if 5 / 3 == int 5 / 3
print "test 2" if 5 / 5 == int 5 / 5

Output:

test 2

There a way more better, faster and elegant ways to check this than using a RegExp.

Upvotes: 0

Related Questions