Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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

by Eily (Hermit)
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.


Comment on Re: Not getting desire output by using switch statement in Perl
Select or Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (14)
As of 2014-04-17 17:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (453 votes), past polls