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.

Replies are listed 'Best First'.
Re^2: Not getting desire output by using switch statement in Perl
by rammohan (Acolyte) on Jan 06, 2014 at 12:08 UTC
    i don't get how it works this script for case. Please could explain your script ... when i execute your script I'm getting this output
    Else 5 12 12 15 Else Else 15 18 12 4
    . What this output could you please explain this..

      How does the output differ from the output you expect?

      For example, it seems to me that e should map to 5 and l should map to 12 from your problem description.