http://www.perlmonks.org?node_id=709176


in reply to Re: Perl 5.10 given/when tricks and caveats
in thread Perl 5.10 given/when tricks and caveats

You may be right about the presentation of that example. I arrived at the code showing the differences through a bit of a convoluted process. I was playing with the differences in a few directions for myself to decide just what to show. I think the code I posted before shows as much about that process as about the resulting idea for the post. Hopefully your idea presents it more clearly to those of you whose voices are outside my head. ;-)

Here's the new C and Perl code and their output:

Perl code:

#!/usr/local/bin/perl use feature qw{ switch }; use strict; use warnings; sub match { my $i = 0; my $foo = shift; given ( $foo ) { when ( 1 ) { $i++; continue; } when ( 2 ) { $i++; continue; } when ( 3 ) { $i++; continue; } when ( 4 ) { $i++; } } print "$foo: $i\n"; } match 1; match 2; match 3; match 4; match 5;

C code:

#include <stdio.h> #include <stdlib.h> int match ( int foo ) { int i = 0; switch ( foo ) { case 1: i++; case 2: i++; case 3: i++; case 4: i++; break; } printf( "%d: %d\n", foo, i ); } int main ( int argc, const char **argv ) { match( 1 ); match( 2 ); match( 3 ); match( 4 ); match( 5 ); exit( 0 ); }

And here's the new output for the Perl:

1: 1 2: 1 3: 1 4: 1 5: 0
And the C:
1: 4 2: 3 3: 2 4: 1 5: 0