C风格的运算符&&,||...和它们的Perl人类可读版本" and"," or",... 之间有什么区别?
互联网代码似乎使用它们:
open (FILE, $file) or die("cannot open $file");
open (FILE, $file) || die("cannot open $file");
Run Code Online (Sandbox Code Playgroud) 我有一个我要排序的数组数组.数组A的每个元素是一个包含3个元素的数组.数组A看起来像:
my @A = ([2,3,1], [1,2,3], [1,0,2], [3,1,2], [2,2,4]);
Run Code Online (Sandbox Code Playgroud)
我想按升序排序A. 比较2个元素时,使用第一个数字.如果存在平局,则使用第二个数字,然后使用第三个数字.
这是我的代码.我使用函数'cmpfunc'来比较2个元素.
sub cmpfunc {
return ($a->[0] <=> $b->[0]) or
($a->[1] <=> $b->[1]) or
($a->[2] <=> $b->[2]);
}
my @B = sort cmpfunc @A;
print "Result:\n";
for my $element (@B) {
print join(",", @{$element}) . "\n";
}
Run Code Online (Sandbox Code Playgroud)
结果:
1,2,3
1,0,2
2,3,1
2,2,4
3,1,2
Run Code Online (Sandbox Code Playgroud)
结果有些分类,但不正确.我的期望是:
1,0,2
1,2,3
2,2,4
2,3,1
3,1,2
Run Code Online (Sandbox Code Playgroud)
我的比较函数有错误吗?奇怪的是,当我将比较代码放入块中时,结果被正确排序.
my @C = sort { ($a->[0] <=> $b->[0]) or
($a->[1] <=> $b->[1]) or
($a->[2] <=> $b->[2]) } @A;
Run Code Online (Sandbox Code Playgroud) 这是真的,在大多数情况下,在Ruby中,最好是使用&&,||而不是and,or除非是一些特殊的情况.
我认为Ruby的一个设计原则是尽可能减少意外,因此使用and或or实际上有一些惊喜......例如and没有比优先级更高的优先级or,而&&优先级高于||.
所以我认为在大多数情况下,使用&&,||.在知道某些特殊情况下,可能需要使用and,or但我认为,如果这些与混合&&,||早晚可能会创建的错误时,你的同事谁在Ruby中开始就在不久前需要编辑的代码.
可能重复:
Ruby中的i = true和false是真的吗?
Perl(或,和)和(||,&&)短路运营商之间有什么区别?
Ruby:||之间的区别 和'或'
是||一样or的Rails的?
案例A:
@year = params[:year] || Time.now.year
Events.all(:conditions => ['year = ?', @year])
Run Code Online (Sandbox Code Playgroud)
将产生以下SQL script/console:
SELECT * FROM `events` WHERE (year = 2000)
Run Code Online (Sandbox Code Playgroud)
案例B:
@year = params[:year] or Time.now.year
Events.all(:conditions => ['year = ?', @year])
Run Code Online (Sandbox Code Playgroud)
将产生以下SQL script/console:
SELECT * FROM `events` WHERE (year = NULL)
Run Code Online (Sandbox Code Playgroud) 我正在使用Perl编写一个小脚本,我很困惑哪个逻辑运算符必须用于比较字符串
示例代码:
if (($app eq "appname1")OR($app eq "appname2")OR($app eq "appname3"))
Run Code Online (Sandbox Code Playgroud)
我必须使用OR(或)||
我有多列的制表符分隔数据.
我在第31列中有操作系统名称,在第6列和第7列中有数据字节.我想要做的是计算每个唯一操作系统的总容量.
所以,我在Perl中做了这样的事情:
#!/usr/bin/perl
use warnings;
my @hhfilelist = glob "*.txt";
my %count = ();
for my $f (@hhfilelist) {
open F, $f || die "Cannot open $f: $!";
while (<F>) {
chomp;
my @line = split /\t/;
# counting volumes in col 6 and 7 for 31
$count{$line[30]} = $line[5] + $line[6];
}
close (F);
}
my $w = 0;
foreach $w (sort keys %count) {
print "$w\t$count{$w}\n";
}
Run Code Online (Sandbox Code Playgroud)
所以,结果会是这样的
Windows 100000
Linux 5000
Mac OSX 15000
Android 2000 …Run Code Online (Sandbox Code Playgroud)