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

Hi Guys,

I'm writing a perl program to get an array of numbers/charaters and add the number but when the character "q" or "Q" if received it should exit.

print "Enter a array of any number of elements \n"; @x=<>; chomp @a; print "@x \n"; foreach(@x) { if(($_>0)&&($_<21)) { $y+=$_; print "Inside sum logic $_\n"; } elsif(($_ eq "q")||($_ eq "Q")) { print "Inside last $_ \n"; last; } }

but for some reason i don't see my check for "q" or "Q" getting true! Can somebody suggest what could be the problem?

Thanks :)

Replies are listed 'Best First'.
Re: simple perl program not working
by GrandFather (Saint) on Oct 15, 2014 at 22:21 UTC
    Can somebody suggest what could be the problem?

    Yep. You don't use strictures: use strict; use warnings;

    If you did you'd notice that you assign some stuff to @x then chomp @a.

    Get into the habit of using sensible variable names even for trivial one off scripts. Single letter variable names are almost never meaningful and in some cases ($a and $b in particular - see sort) conflict with built in variables.

    Perl is the programming world's equivalent of English
Re: simple perl program not working
by AnomalousMonk (Archbishop) on Oct 16, 2014 at 00:22 UTC

    After use-ing warnings (which will let Perl make some suggestions about possible problems) and strict, consider looking at the differences between  <> and  <STDIN> as they may apply to your problem:

    c:\@Work\Perl>perl -wMstrict -le "print qq{Enter a array of any number of elements}; ;; my @x = <>; printf 'A:'; printf qq{ '$_'} for @x; print ''; ;; chomp @x; printf 'B:'; printf qq{ '$_'} for @x; " Enter a array of any number of elements 1 22 333 Q 444 55 66 77 ^Z A: '1 22 333 Q 444 ' '55 66 ' '77 ' B: '1 22 333 Q 444' '55 66' '77'
    (Note that as I'm on a Windoze system,  ^Z (control-Z) terminates  <> input; it's  ^D on *nix IIRC.)

Re: simple perl program not working
by karlgoethebier (Abbot) on Oct 16, 2014 at 09:09 UTC

    I tried to guess what you really wanted ;-)

    Please see also perlsyn.

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»