On Thu, Oct 6, 2011 at 03:10, Shlomi Fish <shlo...@shlomifish.org> wrote:
> Furthermore, I think you can only put when inside given and not arbitrary 
> code,
> and that "when()" operates on the datum that was given to given().

I don't think there's any restriction on what code can be inside the
'given' block -- at least, there's nothing in 'perlsyn' saying you
can't have other code in there.

You are correct that 'given()' sets up a (lexically scoped, I guess?)
$_ equal to the argument that it is given -- which is a copy, not an
alias -- and the smart matches in when() will then use that $_ -- but
if you have a 'when()' that doesn't check $_, then you're fine. See
sample code below.

Note: that is not say that any of this is *advisable* -- it's not,
unless you really really need to. (You don't really really need to, in
case you're wondering.) You're probably better off only having
'when()' blocks inside a 'given()' block, and you're probably better
off keeping the conditions in your 'when()' tests nice and simple.
You'll thank yourself down the road.

Sample code:

#! /usr/bin/env perl

use strict;
use warnings;
use feature 'switch';

$_ = 'outside';

my $foo = 'foo';

given( $foo ) {
  when( 1 == 1 ) { print "INIT\n" ; continue }

  when( 'bar' )  { print "BAR: $foo $_\n" }

  $foo = 'bar';

  when( 'foo' )  { print "FOO: $foo $_\n" }

  $foo = 'baz';

  when( 'outside' ) { print "OUT: $foo $_\n" }

  default { print "DEF: $foo $_\n" }
}

print;

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to