views:

220

answers:

2

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" } }
+3  A: 

In a recent answer to Zaid's question Strategies to handle a file with multiple fixed formats, I ended up with a poor man's yacc whose main loop searched an array of regular expressions for the first match:

while (<>) {
  given($_) {
    when (@{[ map $pattern{$_}, @expect ]}) {}
    default {
      die "$0: line $.: expected " . join("|" => @expect) . "; got\n$_";
    }
  }
}

In another question, David B wanted to match against multiple regexes, and my answer uses smart matching to implicitly loop over the regexes:

#! /usr/bin/perl

use warnings;
use strict;

use feature 'switch';

my @patterns = (
  qr/foo/,
  qr/bar/,
  qr/baz/,
);

for (qw/ blurfl bar quux foo baz /) {
  print "$_: ";
  given ($_) {
    when (@patterns) {
      print "hit!\n";
    }
    default {
      print "miss.\n";
    }
  }
}
Greg Bacon
The `given` statement is a little annoying. Is there a reason that `while` can't be used as a topicalizer?
Michael Carman
+1  A: 

Don't know if below is a neat use case or just a tip of the hat to Perl's linguistic lineage :)

# things todo (or should have done!) at this time of the day:

given (TheTime->of_day) {

    when ('morning') {
        breakfast();
        make_packed_lunch() if $_->is_work_day;
    }

    lunch() when 'afternoon';

    when ('evening') {
        goto_pub() if $_->is_friday;
        dinner();
    }

    default { say "Should be sleeping if its " . $_->{dt}->ymd }
}

And if you view $_ has "it" then it works particular well (IMHO).

The above works by overloading the smart match operator which given/when rely on. Here is how TheTime class could be written to make my example work:

{
    package TheTime;
    use DateTime;
    use overload '~~' => '_check_hour', fallback => 1;

    our %day_time = (
        morning   => [0..11],
        afternoon => [12..17],
        evening   => [18..23],
    );

    sub of_day {
        my $class = shift;
        bless {
            dt => DateTime->now,
        }, $class;
    }

    sub is_work_day { shift->{dt}->day_of_week ~~ [1..5] }
    sub is_friday   { shift->{dt}->day_of_week == 5      }

    sub _check_hour {
        my ($self, $greeting) = @_;
        $self->{dt}->hour ~~ $day_time{$greeting};
    } 
}

/I3az/

PS. Also see this blog post i did recently: given/when – the Perl switch statement

draegtun
+1: nice use of `overload`
drewk