What kind of syntactic sugar is available in Perl to reduce code for l/rvalue operators vs. if statements?

后端 未结 5 1490
时光说笑
时光说笑 2021-02-13 04:26

There\'s a bunch out there, as Perl is a pretty sugary language, but the most used statements in any language is the combination of if statements and setting values. I think I\

5条回答
  •  春和景丽
    2021-02-13 04:34

    These structures from your question could be written a little bit more clearly using the low precedence and and or keywords:

    $c and return $r;    # return $r if ($c);
    $c or return $r;     # return $r unless ($c);
    $c and $r = $s;      # $r = $s if ($c);
    

    The nice thing about and and or is that unlike the statement modifier control words, and and or can be chained into compound expressions.

    Another useful tool for syntactic sugar is using the for/foreach loop as a topicalizer over a single value. Consider the following:

    $var = $new_value if defined $new_value;
    

    vs

    defined and $var = $_ for $new_value;
    

    or things like:

    $foo = "[$foo]";
    $bar = "[$bar]";
    
    $_ = "[$_]" for $foo, $bar;
    

    the map function can also be used in this manner, and has a return value you can use.

提交回复
热议问题