我正在尝试使自己适应来自Perl,R,C和其他几种语言的PHP.
问题:
>是否有PHP替代下面的Perl语法糖?
$y= $x || "I am undefined"; ## Default value
($x==1) or die "problem with $x"; ## Works under some circumstances
$y= ($x1==1) ? 2 : ($x2==2) ? 3 : ($x3==3) ? 2 : 5; ## Chaining needs () in PHP
print "Val: $array[$x]"; ## Does not work with $_SESSION[...] in PHP
当然,我可以编写更长的具有相同功能的函数/构造,但是也许有标准的PHP简短方法可以替换这些相当常见的有用构造.
>我的其他语言经验并未暗示PHP具有什么语法糖?
解决方法:
1.
您可以将?:视为||在perl中,但实际上是三元/(trinary?)运算符,其中省略了第二个参数,并暗示第一个($x).
$y= $x ?: "I am undefined"; # not before v5.3.x
您不能($x == 1)或return | break | continue;因此,您必须使用常规if条件(对于单个语句,可以省略大括号)
if (!($x==1)) break;
至于三元链,恐怕事情并不简单,因为您想让它像在perl中那样工作
$y = ($x1==1 ? 2 :
($x2==2 ? 3 :
($x3==3 ? 2 : 5
))); // close as many times as there is rows above
如果变量未在双引号内插值,则可以使用大括号,
print "Val: {$array[$x]}";
2.
至于语法糖,你可以使用
$arg += array(
"default" => 55,
);
就像你会
%arg = ("default" => 55, %arg);
在perl中,以便为缺少的哈希键提供默认值.
标签:php,perl
来源: https://codeday.me/bug/20191027/1946896.html