Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Not getting desire output by using switch statement in Perl

by Eily (Monsignor)
on Jan 06, 2014 at 12:02 UTC ( #1069495=note: print w/replies, xml ) Need Help??

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1069495]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2020-09-21 15:37 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (126 votes). Check out past polls.