ivo Welch
ivo Welch

Reputation: 2866

PHP syntactic sugar vs. Perl

I am trying to orient myself in PHP, coming from Perl, R, C, and a couple of other languages.

Questions:

  1. Are there PHP-isms to replace the following Perl syntax sugar?

    $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
    

    Of course, I can write longer function/constructs that have the same functionality, but maybe there are standard PHP short ways to replace these fairly common useful constructs.

  2. What syntactic sugar does PHP have that my other language experience does not suggest?

Upvotes: 3

Views: 423

Answers (1)

mpapec
mpapec

Reputation: 50647

1.

You can think of ?: as || in perl, but it is actually ternary/(trinary?) operator where second parameter is omitted and implies first one ($x).

$y= $x ?: "I am undefined"; # not before v5.3.x

You can't ($x==1) or return|break|continue; so you have to use regular if condition (braces can be omitted for single statements)

if (!($x==1)) break;

As for chaining ternary, I'm afraid that things are not simple as you think if you want it to work like in perl

$y = ($x1==1 ? 2 :
     ($x2==2 ? 3 :
     ($x3==3 ? 2 : 5
))); // close as many times as there is rows above

You can use braces if your variable does not interpolate inside double quotes,

print "Val: {$array[$x]}";

2.

As for syntactic sugar you can use

$arg += array(
  "default" => 55,
);

like you would

%arg = ("default" => 55, %arg);

in perl in order to give default values for missing hash keys.

Upvotes: 4

Related Questions