You are viewing the version of this documentation from Perl 5.14.1. View the latest version
when EXPR BLOCK
when BLOCK

when is analogous to the case keyword in other languages. Used with a foreach loop or the experimental given block, when can be used in Perl to implement switch/case like statements. Available as a statement after Perl 5.10 and as a statement modifier after 5.14. Here are three examples:

    use v5.10;
    foreach (@fruits) {
        when (/apples?/) {
            say "I like apples."
        }
        when (/oranges?/) {
            say "I don't like oranges."
        }
        default {
            say "I don't like anything"
        }
    }

    # require 5.14 for when as statement modifier
    use v5.14;
    foreach (@fruits) {
	say "I like apples." 	    when /apples?/; 
	say "I don't like oranges." when /oranges?;
        default { say "I don't like anything" }
    }

    use v5.10;
    given ($fruit) {
        when (/apples?/) {
            say "I like apples."
        }
        when (/oranges?/) {
            say "I don't like oranges."
        }
        default {
            say "I don't like anything"
        }
    }

See "Switch statements" in perlsyn for detailed information.