2014-06-12 184 views
1

我可以同時做匹配模式和算術運算嗎?Perl模式匹配和算術運算

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

結果5,爲什麼?

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

total correct。 我怎麼能在一個表達?

回答

5

操作的默認順序是給你意想不到的結果。相反,嘗試:

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

但是,正如其他人所指出的,這是測試是否3個分歧5.您有用於該模運算符一個可怕的方式:

print 5 % 3 == 0; 
1

它返回5因爲3 !~ /\.\d*/返回1和5/1 = 5`。

你可以用你的算術表達式中括號有Perl的第一評價它:

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

@ WumpusQ.Wumbley謝謝,測試時我錯過了那一個。 –

0

你只需要使用括號!

什麼在你的代碼happend基本上是:

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

所以正則表達式是第一位的,然後是/師。

我想你想要做的事,如:

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! 

如果我理解你的問題是正確的,你只是想,如果分工不返回浮動打印:

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

輸出:

test 2 

有一種比使用RegEx更好,更快,更優雅的方法來檢查此問題頁。

+0

謝謝,我想要什麼,我不能投你一個對不起 –

+0

現在你可以:P。 –