[Melbourne-pm] Perl switch statements

Michael G Schwern schwern at pobox.com
Mon Oct 22 16:24:50 PDT 2012


On 2012.10.21 10:51 PM, Toby Corkindale wrote:
> Why is the result good enough to return but not to assign?

given doesn't return anything.  What's tripping you up there is that in the
absence of an explicit return, a subroutine or do block returns the last
evaluated expression.  That includes if/else and while loops but not for
loops.  Before 5.14.0 it didn't include given either.
http://perldoc.perl.org/5.14.0/perldelta.html#Changes-to-Syntax-or-to-Perl-Operators

That's why golfing horrors like this work:

    sub foo {
        if( 1 ) {
            "foo";
        }
        else {
            "bar";
        }
    }
    say foo();

If you see that the author is either A) falsely lazy or B) still thinks return
incurs a performance penalty which was like 15 years ago.

There's been plenty of clamoring for given to actually be usable in the right
hand side of an expression.  I'm not sure what the status of that is, I
thought it was a done deal.  Right now in order to do that you have to wrap it
in a do block.

	my $value = do {
	    given ($grade) {
	        'Well done!'        when 'A';
	        'Try harder!'       when 'B';
	        'You need help!!!'  when 'C';
	        default { 'You are just making it up!' }
	    }
	};


-- 
ROCKS FALL! EVERYONE DIES!
	http://www.somethingpositive.net/sp05032002.shtml


More information about the Melbourne-pm mailing list