2006-04-01 'Perl中不寻常的 ?: 运算符'

1
\$data->{\$id}->{'total'} ?
2
\$data->{\$id}->{'ratio'} = sprintf("%.2f%%", 100 * \$data->{\$id}->{'succ'} / \$data->{\$id}->{'total'}) :
3
\$data->{\$id}->{'ratio'} = 'N/A';
Copied!

1
if ( \$data->{\$id}->{'total'} ) {
2
\$data->{\$id}->{'ratio'} = sprintf("%.2f%%", 100 * \$data->{\$id}->{'succ'} / \$data->{\$id}->{'total'});
3
} else {
4
\$data->{\$id}->{'ratio'} = 'N/A';
Copied!

Ternary `?:` is the conditional operator, just as in C. It works much like an if-then-else. If the argument before the ? is true, the argument before the : is returned, otherwise the argument after the : is returned.

1
\$data->{\$id}->{'total'} ?
2
( \$data->{\$id}->{'ratio'} = sprintf("%.2f%%", 100 * \$data->{\$id}->{'succ'} / \$data->{\$id}->{'total'}) ) :
3
( \$data->{\$id}->{'ratio'} = 'N/A' );
Copied!
...居然就对了。既然是return the argument，我就又换了一种方式：
1
\$data->{\$id}->{'ratio'} = \$data->{\$id}->{'total'} ?
2
sprintf("%.2f%%", 100 * \$data->{\$id}->{'succ'} / \$data->{\$id}->{'total'}) :
3
'N/A';
Copied!

1
#!/usr/bin/perl
2
3
use strict;
4
5
my \$total=1;
6
my \$rval;
7
8
############################`
9
\$total ?
10
\$rval = \$total :
11
\$rval = 'N/A';
12
13
print \$rval, "\n";
14
15
############################
16
\$total ?
17
( \$rval = \$total ) :
18
( \$rval = 'N/A' );
19
20
print \$rval, "\n";
21
22
############################
23
\$rval = \$total ? \$total : 'N/A';
24
25
print \$rval, "\n";
26
27
############################
28
if (\$total) {
29
\$rval = \$total;
30
} else {
31
\$rval = 'N/A';
32
}
33
34
print \$rval;
Copied!