phimtau123 has asked for the wisdom of the Perl Monks concerning the following question:

I'm using the switch statement to make use of some information in a file and print it out...The problem is there are two field in the file that are similiar...Code and UserCode....so when i switch on 'code' it sometime print out the value for UserCode...Is there a way i can fix this?

Replies are listed 'Best First'.
Re: Case Statement
by Joost (Canon) on May 25, 2007 at 20:12 UTC
      switch ($array[0]) { case (/Time_Stamp/i) { @time = split (/-/, $array[1]); $date_submited = $time[0]; $time_submited = $time[1]; } case (/eqpid/i) { $eqpid = $array[1]; # $eqpid=substr ($array[1], -1, 1, ); $chambernum = substr ($array[1], -1, 1); switch ($chambernum){ case (/A/i) {$chamber = 1;} case (/B/i) {$chamber = 2;} case (/C/i) {$chamber = 3;} case (/D/i) {$chamber = 4;} } } case (/AlarmType/i) {$alarmtype = "$array[1]";} case (/LotID/i) { @lotid = split( /-/, $array[1] ); $lotid = "$lotid[0]"; $wafer_flow = "$lotid[1]-$lotid[2]"; } case (/Code/i) {$code = "$array[1]";} case (/UserCode/i) { # $usercode = "$array[1]"; print "User = $array[1]"; } look at the case for code and Usercode
        I'd be more inclined to use a hash whose keys are the appropriate case values, some of which would be regexes to deal with Code/UserCode.
        phimtau123:

        It appears that $array[0] is the field name and that you're using regular expressions to get case insensitivity. If that's the case, you could let too much junk through since your switch statement is looking for words with any matching substring. You might instead just change your code to map things to upper or lower case for the comparison, like:

        switch (uc($array[0])) { case (uc("Time_Stamp")) { @time = split (/-/, $array[1]); $date_submited = $time[0];
        Also, you should quit putting quotes around your variable references. It slows things down, and can cause you some problems. For example, check the result of the following line when @lotid contains 0, 2, 4.
        $wafer_flow = "$lotid[1]-$lotid[2]";
        ...roboticus

        Assuming /Time_Stamp/i really means /^Time_Stamp\z/i,

        my @array = ...; my %dispatch = ( time_stamp => sub { @time = split (/-/, $array[1]); $date_submited = $time[0]; $time_submited = $time[1]; }, ... ); my $func = $dispatch{lc($array[0])}; if ($func) { $func->(); } else { ... }
Re: Case Statement
by holli (Abbot) on May 26, 2007 at 20:20 UTC
    Joost is absolutely right. Switch is a source filter (a module that manipulates your perl code) and is as such inherently and actually buggy. If you really can't live without it, install the newest perl and use the new given-syntax. Otherwise, use if-else or a dispatch table.


    holli, /regexed monk/
Re: Case Statement
by planetscape (Chancellor) on May 27, 2007 at 17:24 UTC