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


in reply to Not getting desire output by using switch statement in Perl

$a eq 'a' || 'b' does not mean "$a is equal to ('a' or 'b')" but rather "return true if $a is equal to 'a', or return 'b'", which means everytime $a fails to match 'a', 'b' is returned instead. Your code would work with:

given ($a) { when ('a') { print 1}; when ('b') { print 2}; ... }
But given is experimental (Edit: I first wrote deprecated, but choroba pointed out the mistake), so you shouldn't use it. And the fact that you had to do 26 times the same thing (I hope you used copy and paste) is a clear indication that there is something wrong with your code. And you should not have variables called $a and $b, perl has other uses for them, and might change their values without warning.

Here is a simpler solution using ord

$\ = "\n"; # add a line break after each print, say could be used inst +ead for my $char (split //, "Hello World") { if ($char =~ /[a-z]/) # if the char is between a and z { print 1 + ord($char) - ord('a'); } else { print "Else"; } }
It could be even shorter, but I believe this will be easier to understand.