我在Mac OS X v10.7.2(Lion(上的Perl v5.12.3中运行以下程序:
#!/usr/local/bin/perl
use strict;
use warnings;
use DBI;
my $db = DBI->connect("dbi:SQLite:testdrive.db") or die "Cannot connect: $DBI::errstr";
my @times = ("13:00","14:30","16:00","17:30","19:00","20:30","22:00");
my $counter = 1;
for (my $d = 1; $d < 12; $d++) {
for (my $t = 0; $t < 7; $t++) {
# Weekend days have seven slots, weekdays
# have only four (barring second friday)
if (($d+4) % 7 < 2 || ($t > 3)) {
$db->do("INSERT INTO tbl_timeslot VALUES ($counter, '$times[$t]', $d);");
$counter++;
# Add 4:00 slot for second Friday
} elsif (($d = 9) && ($t = 3)) {
$db->do("INSERT INTO tbl_timeslot VALUES ($counter, '$times[$t]', $d);");
$counter++;
}
}
}
$db->disconnect;
我得到了一个";Found=在条件中,应为==在addtimes.pl行16";警告,但这条线上没有等号。此外,循环似乎从$d == 9
开始。我错过了什么?
第16行:
if (($d+4) % 7 < 2 || ($t > 3)) {
问题出在elsif
中
} elsif (($d = 9) && ($t = 3)) {
^-----------^--------- should be ==
因为if
语句从第16行开始,而elsif
是该语句的一部分,所以这就是报告错误的地方。这是Perl编译器的一个不幸限制。
在一个无关的问题上,尽可能避免C风格的循环要好得多:
for my $d ( 1 .. 11 ) {
...
for my $t ( 0 .. 6 ) {
...
}
}
那不是更漂亮吗?:(
} elsif (($d = 9) && ($t = 3)) {
这一行将把9
分配给$d
,把3
分配给$t
。正如警告所说,你可能想要这个:
} elsif (($d == 9) && ($t == 3)) {