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

后端 未结 5 1482
时光说笑
时光说笑 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:38

    One of the biggest called for features in Perl was the switch statement. This finally appeared in Perl 5.10. I'm just using the example from the documentation:

    use feature qw(say switch);  #My preference
    #use feature ":5.10";        #This does both "say" and "switch"
    
    [...]
    
    given($foo) {
        when (undef) {
            say '$foo is undefined';
        }
        when ("foo") {
            say '$foo is the string "foo"';
        }
        when ([1,3,5,7,9]) {
            say '$foo is an odd digit';
            continue; # Fall through
        }
        when ($_ < 100) {
            say '$foo is numerically less than 100';
        }
        when (\&complicated_check) {
            say 'a complicated check for $foo is true';
        }
        default {
            die q(I don't know what to do with $foo);
        }
    }
    

    Why o' why did they go with given/when and not switch/case like you find in most languages is a mystery to me. And, why if the statement is given/when, do you specify it in use features as switch?

    Alas, the people who made these decisions are at a higher plane than I am, so I have no right to even question these luminaries.


    I avoid the more exotic stuff, and stick with the easiest to understand syntax. Imagine the person who has to go through your code and find a bug of add a feature, which would be easier for that person to understand:

    $r &&= $s;
    

    or

    if ($r) {
        $r = $s;
    }
    

    And, maybe I might realize that I really meant:

    if (not defined $r) {
        $r = $s;
    }
    

    And, in this case, I might even say:

    $r = $s if not defined $r;
    

    Although I don't usually like post-fixed if statements because people tend to miss the if part when glancing through the code.

    Perl is compiled at runtime, and the compiler is fairly efficient. So, even though it's way cooler to write $r &&= $s and it earns it earns you more geek points and is less to type, it doesn't execute any faster. The biggest amount of time spent on code is on maintaining it, so I'd rather skip the fancy stuff and go for readability.

    By the way, when I think of syntactic sugar, I think of things added to the language to improve readability. A great example is the -> operator:

    ${${${$employee_ref}[0]}{phone}}[0];
    

    vs.

    $employee_ref->[0]->{phone}->[0];
    

    Of course, if you're storing data as a reference to a list to a hash to a list, you are probably better off using object oriented coding.

提交回复
热议问题