Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl switch not falling through properly?

I have a value ($field) that I want to test. Read the perl doc (http://perldoc.perl.org/Switch.html#Allowing-fall-through), and figured that I had this nailed. Seems not, because if I pass 'Exposure Bias', there is no output, though 'Exposure Bias Value' works as it should. It throws no errors, so I have no clue.

use Switch;
use strict; use warnings;

my $field = 'Exposure Bias';

switch($field){
    case 'Exposure Bias' {next;}
    case 'Exposure Bias Value' {print "Exp: $field\n";}
}

Update

I'm assuming the wrong thing it seems. What I want to do with this switch is have the print run if either case is matched. I thought that next would pass control on to the next case's code, but that was my mistake.

How do I code this so that the code in the second case runs if the first case is matched?


Working Solution

given($field){
    when(['Exposure Bias','Exposure Bias Value']){print "Exp: $field\n";}
}
like image 515
Ben Dauphinee Avatar asked Dec 18 '22 00:12

Ben Dauphinee


1 Answers

DVK's comments about why your switch isn't working as you expect are correct, but he neglects to mention a better, safer way to implement your switch.

Switch is built using source filters and has been deprecated and is best avoided. If you are working with Perl 5.10 or newer, use given and when to build your switch statement:

use strict;
use warnings;

use feature qw(switch);

my $field = 'Exposure Bias';

given($field) {
    when ([ 
        'Exposure Bias', 
        'Exposure Bias Value',
    ]) {
        print 'Exp: ' . $field . "\n"; 
    }
}

See perlsyn for more info.

like image 78
daotoad Avatar answered Jan 09 '23 23:01

daotoad