What kind of neat use cases exist for given/when?

Perl 5.10 introduced a proper switch construct with given/when and it seems like a powerful tool.

Currently however, perldoc perlsyn lacks some good examples.

One case where I found it handy lately was for using it with file test operators:

given (-d "foo/bar/") {
    when (1) { ... } # defined is wrong as -d returns '' on a file.
    default { ... }
}

or alternatively:

given ("foo/bar/") {
    when (-d) { ... }
    default { ... }
}

For me, especially the first version looks better than an if-else construct or using the ternary operator, when depending on the outcome of the test I need to perform actions in both cases.

It made me wonder though, what else looks neat beyond the simple case of falling back to smart matching and avoiding overlong if-elsif-elsif-...-else structures?

I have a hunch that given/when makes it possible to be clever without losing clarity, but I don't have any good examples.

One thing that surprised me though, is that you can nest the construct aswell:

given ($filename) {
        when (-e) {
                when (-f) {
                        when (-z) { say "Empty file" }
                        default { say "Nonempty file" }
                }
                when (-d) {
                        when (-o) { say "Directory owned by me"}
                        default { say "Directory owned by someone else" }
                }
                default { say "Special" }
        }
        default { say "No such file or directory" } }
10
задан szbalint 3 September 2010 в 19:46
поделиться