talexb has asked for the wisdom of the Perl Monks concerning the following question:
Growing up with an actuary as a Father meant lots of mathematics while growing up. OK, I had an aptitude for it, that helped. There were a lot of number and word games, and one of them was called fizz-buzz. You could play it anywhere, around the dinner table, while out for a walk in the Morgan Arboretum, or on a long car ride to or from Cape Cod. It goes like this:
The players recite the numbers in ascending order, starting at 1, except when you get to a multiple of 3, you say 'fizz', and when you get to a multiple of 5 you say 'buzz'. The number before 16, is, of course, fizz-buzz. To make things more interesting and a bit more challenging, my Father added 'sausage' when the number was a multiple of 7, thus the trifecta was fizz-buzz-sausage after 104 turns.
This morning I wanted to try out Perl's new switch statement ..
#!/usr/bin/perl510 use feature 'switch'; use feature 'say'; { for ( 1..40 ) { my @what; given ( $_ ) { when ( $_ % 3 == 0 ) { push ( @what, 'fizz' ); } when ( $_ % 5 == 0 ) { push ( @what, 'buzz' ); } when ( $_ % 7 == 0 ) { push ( @what, 'sausage' ); } } say join(' ',$_,@what); } }
but found it didn't produce the output I expected. Unlike C's switch statement, once a condition is met, the entire given construct is finished.
1 2 3 fizz 4 5 buzz 6 fizz 7 sasusage 8 9 fizz 10 buzz 11 12 fizz 13 14 sasusage 15 fizz 16 17 18 fizz 19 20 buzz 21 fizz 22 23 24 fizz 25 buzz 26 27 fizz 28 sasusage 29 30 fizz 31 32 33 fizz 34 35 buzz 36 fizz 37 38 39 fizz 40 buzz
That's OK -- now I know. Oh, and to get this to run, I had to run Perl 5.10 from the directory I built it in, and include -Ilib on the command line (thanks mauke). I made the mistake of upgrading the system Perl one time, and that's a mistake I won't ever make again.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Perl 5.10: switch statement demo
by Limbic~Region (Chancellor) on Dec 19, 2007 at 20:24 UTC | |
by ikegami (Patriarch) on Dec 19, 2007 at 22:32 UTC | |
by talexb (Chancellor) on Dec 20, 2007 at 16:26 UTC | |
by ikegami (Patriarch) on Dec 20, 2007 at 21:27 UTC | |
by talexb (Chancellor) on Dec 20, 2007 at 21:30 UTC | |
Re: Perl 5.10: switch statement demo
by jdporter (Chancellor) on Dec 19, 2007 at 20:26 UTC | |
Re: Perl 5.10: switch statement demo
by Thilosophy (Curate) on Dec 20, 2007 at 01:34 UTC | |
Re: Perl 5.10: switch statement demo
by ikegami (Patriarch) on Dec 19, 2007 at 22:48 UTC | |
by talexb (Chancellor) on Dec 20, 2007 at 15:29 UTC | |
Re: Perl 5.10: switch statement demo
by LighthouseJ (Sexton) on Dec 20, 2007 at 13:42 UTC | |
by robin (Chaplain) on Dec 20, 2007 at 18:20 UTC | |
by LighthouseJ (Sexton) on Dec 20, 2007 at 18:43 UTC | |
by robin (Chaplain) on Dec 20, 2007 at 21:18 UTC |