Perl中的If子句

wvt8vs2t  于 7个月前  发布在  Perl
关注(0)|答案(2)|浏览(55)

我有以下代码:

$path = "/srv/www/root/www/data/".$img1;
my $type = `file $path`;

unless ($type =~ /JPEG/i
 || $type =~ /PNG/i) {
   print "The file is not a valid JPEG or PNG.";
}

字符串
我是perl新手,我想把它改成if(isimagefile) perform this set of code; else perform this set of code
我不明白的是这里的逻辑。我不知道=~是什么,我不明白unless的逻辑

更新

以下是我目前的逻辑:

$path = "/srv/www/root/www/data/".$img1;
my $type = `file $path`;
if($type =~ /JPEG/i || $type =~ /PNG/i || $type=~ /JPG/i){

}


但好像不管用。

s4n0splo

s4n0splo1#

正如Quentin已经说过的,=~是一个正则表达式测试。在你的例子中,它测试$type * 是否包含 * 短语JPEG。斜杠/是正则表达式语法的一部分。有关详细信息,请参阅Perl's tutorial
另外,unless正好与if相反。有些人在想表达if (not …)时使用它。我个人认为这种做法不好,因为它降低了可读性,特别是当条件由多个部分组成并且其中包含!时,如unless($a>5 || ($a!=7 && (!$b)))。要弄清楚条件何时匹配是一件可怕的事情。
所以代码

unless ($type =~ /JPEG/i || $type =~ /PNG/i) {
   print "The file is not a valid JPEG or PNG.";
}

字符串
可以重写为

if ( ! ($type =~ /JPEG/i || $type =~ /PNG/i) ) {
   print "The file is not a valid JPEG or PNG.";
} else {
   print "The file IS a valid JPEG or PNG.";
}


或者反过来(代码块和条件交换):

if ( $type =~ /JPEG/i || $type =~ /PNG/i ) {
   print "The file IS a valid JPEG or PNG.";
} else {
   print "The file is not a valid JPEG or PNG.";
}


这可以通过将两个条件连接起来,将它们移动到正则表达式中并在那里进行OR运算来进一步简化:

if ( $type =~ /(JPEG|PNG)/i ) {
   print "The file IS a valid JPEG or PNG.";
} else {
   print "The file is not a valid JPEG or PNG.";
}


倒数第二个代码段转换为 “if($type contains JPEG)or($type contains PNG)",而最后一个代码段转换为 “if $type contains(JPEG or PNG)"。结果是相同的,但$type和正则表达式只被考虑一次,这(理论上)使其更快。
在你的尝试中,你也引用了JPG(没有E)。这也可以用正则表达式来表达,因为JPG就像JPEG一样,但是没有E,所以E是可选的。因此:

if ( $type =~ /(JPE?G|PNG)/i ) {
   print "The file IS a valid JPEG, JPG, or PNG.";
} else {
   print "The file is not a valid JPEG or PNG.";
}


?表示E的可选性。同样,请参阅教程。

zsbz8rwp

zsbz8rwp2#

=~测试左手侧与右手侧的the regular expression
unless (condition)等于if (! (condition) )

相关问题