On Sun, Dec 26, 2010 at 06:13:06PM +0100, Peter Daum wrote: > Is it possible to get a value from a given-when statement? > > Suppose I have a long comparison in which all branches affect > the same variable. Here's a short example (minor variation > from"perlsyn"): > > given($something) { > when (/^abc/) { $x = 1; } > when (/^def/) { $x = 2; } > when (/^xyz/) { $x = 3; } > default { $x=-1; } > } > > All the explicit assignments to the same variable are pretty ugly; > With an "if" statement, I can do something like: > > my $x=do { > $_=$something; > if (/^abc/) { 1; } > elsif (/^def/) { 2; } > elsif (/^xyz/) { 3; } > else { -1; } > }; > > but the same thing using the new (well, relatively;) > "given-when" statement does not seem to work: > > $x=do { > given($something) { > when (/^abc/) { 1; } > when (/^def/) { 2; } > when (/^xyz/) { 3; } > default { -1; } > } > }; > > Any ideas?
You will be pleased (or not) to hear that as of perl 5.13.1 you can do just that. If you don't mind living dangerously you could download and install the latest development perl version, 5.13.7. Or you can wait a few months longer until perl 5.14.0 gets released, and then download and install that. Or you can wait until your vendor updates to some perl version >= 5.14.0. Example from the docs: my $price = do { given ($item) { when ([ 'pear', 'apple' ]) { 1 } break when 'vote'; # My vote cannot be bought 1e10 when /Mona Lisa/; 'unknown'; } }; -- Paul Johnson - p...@pjcj.net http://www.pjcj.net -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/