比较和连接perl?

时间:2014-09-09 12:12:18

标签: perl

将字符串与三元运算符连接:

这有效:

 $additional .= "   <tr>
                          <td>$wrow{perc_chng}</td>
                   </tr>";

这不是

$additional .= "    <tr>
                        <td " . $wrow{perc_chng} > 0 ? "bgcolor='#009900'" :
     $wrow{perc_chng} < 0 ? "bgcolor='#009900'" : '' . ">$wrow{perc_chng}</td>
                              </tr>";

并给出:

`Argument ">-29.7625</td>\n^I^I^I^I^I^I  <td 44.5936" isn't numeric in numeric gt (>) at ...` 

我做错了什么?

2 个答案:

答案 0 :(得分:3)

这里发生的是三元运算符?:的{​​{3}}低于数字比较运算符的优先级,如precedence所示。

您可以使用括号来强制执行正确的执行顺序:

$additional .= "   <tr>
                    <td " . ( $wrow{perc_chng} > 0 ? 
"bgcolor='#009900'" : $wrow{perc_chng} < 0 ? 
"bgcolor='#009900'" : '') . ">$wrow{perc_chng}</td>
                      </tr>";

据我了解,如果没有变化(perc_chng == 0),你不想改变颜色,然后你的逻辑会写得更好:

$additional .= "   <tr>
                    <td " . ( $wrow{perc_chng} == 0 ? 
"" : "bgcolor='#009900'" ) . ">$wrow{perc_chng}</td>
                      </tr>";

我相信如果我想影响颜色变化,我会为它使用一个子程序,例如:

sub td_colour {
    my $num = shift;
    if ($num >= 0) {
        return qq(<td bgcolor='#009900'>$num</td>);
    } else {
        return qq(<td>$num</td>);
    }
}

答案 1 :(得分:0)

为了比较字符串,您应该使用运算符:lt而不是<gt而不是>

示例:

#!/usr/bin/perl 

use strict;
use warnings;

if ('aba' > 1) {print "This will not be printed\n"; }
if ('aba' gt 1) {print "but this will be printed\n"; }

输出:

Argument "aba" isn't numeric in numeric gt (>) at test.pl line 6.
but this will be printed
相关问题