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

Hi I am learning Perl using Padre. I am trying to run a piece of code using the "if/else or die" statements. I am giving it 2 choices but it will not recognize either choice and kills it. Can y'all show me what I am doing wrong? Thanks.

print "Your time is almost out make a choice either 1 for Vampire or 2 + for Werewolf. \n"; chomp ($choice=<STDIN>) ; if ($choice== 1) {sub vamp ; } else {die } if ($choice== 2) {sub wolf ; } else {die } sub vamp {print "Congratulations $name on choosing to become a vampire +. I will turn you as requested and be your mentor until I deem you ready to go out o +n your own. \n"; } sub wolf {print "Congratulations $name on choosing to become a werewol +f. I will turn you as requested and introduce you to my pack where you will learn of +your new skills. \n"; }

Replies are listed 'Best First'.
Re: Using If/Else
by LanX (Saint) on Apr 19, 2017 at 20:25 UTC
    Calling with  sub vamp looks very wrong. Do a vamp()

    Same for the other call.

    You are basically redefining the sub again.

    Please use strict and warnings to catch such problems earlier.

    (Untested b/c I'm on mobile)

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

    update

    The next issue will be that the 2 case can never be reached because you'll always die before in the first else .

    Consider using elsif

    if ($choice==1) { ... } elsif ($choice==2) { ... } else { die "wrong choice $choice" }

    See perlsyn#Compound-Statements

Re: Using If/Else
by AnomalousMonk (Archbishop) on Apr 20, 2017 at 00:03 UTC

    In particular, the statement
        sub vamp ;
    is a pre-declaration (update: or perhaps with more terminological accuracy, a forward declaration) of a subroutine with a  vamp identifier. As others have pointed out, it does not call the subroutine. (And likewise for the similar statement with wolf.) Please see the SYNOPSIS in perlsub.


    Give a man a fish:  <%-{-{-{-<

Re: Using If/Else
by Anonymous Monk on Apr 19, 2017 at 20:38 UTC
    Form you're consideration
    print "Your time is almost out make a choice either 1 for Vampire or 2 + for Werewolf. \n"; chomp ($choice=<STDIN>) ; if ($choice== 1) {vamp() ; } if ($choice== 2) {wolf() ; } sub vamp {print "Congratulations $name on choosing to become a vampire +. I will turn you as requested and be your mentor until I deem you ready to go out o +n your own. \n"; } sub wolf {print "Congratulations $name on choosing to become a werewol +f. I will turn you as requested and introduce you to my pack where you will learn of +your new skills. \n"; }