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

Re: new to perl, need some help

by NetWallah (Abbot)
on Oct 02, 2012 at 04:19 UTC ( #996796=note: print w/ replies, xml ) Need Help??


in reply to new to perl, need some help

Welcome!

The first thing monks will tell new perl programmers is to always
use strict;
use warnings

at the start of each program.

That said, your problem is the use of

@values = ();
inside the loop. That re-initializes the @values array each time.
Move that outside the loop, and initialize it like this:
my @values = ();
The Parens are not necessary - perl initializes it to an empty array anyway.
Also, you code could be shortened if you used the "map" and "grep" functions, but I expect you have a ways to go before you are comfortable with them.
But first - get your program working.
Cheers, and all the best.

             I hope life isn't a big joke, because I don't get it.
                   -SNL


Comment on Re: new to perl, need some help
Select or Download Code
Replies are listed 'Best First'.
Re^2: new to perl, need some help
by kingpin007 (Initiate) on Oct 02, 2012 at 04:28 UTC
    Ah okay, thank you so much for that! What a silly mistake I didnt even realize that. And yes, i had actually used grep/map in my code as well to get the same output
    @number = qw(1 2 3 4 5 10 11 12 13 14); @num = map ($_ *$_, (@number)), "\n"; @square = grep ($_ >=100 && $_ <=200, @num); print "Obtaining square values using map/grep: @square \n";
    I just wanted to learn how to do it through a foreach loop. Thanks again for the quick response and help! :)
Re^2: new to perl, need some help
by bimleshsharma (Beadle) on Oct 02, 2012 at 12:05 UTC

    Here is issue with initialisation of array(@values = ();). It is reinitialising on every iteration of loop and ultimately storing last value. Use below hope that will fulfil your requirement

    !#/usr/bin/perl use strict; use warnings; @number = qw(1 2 3 4 5 10 11 12 13 14); print "The values within the array are @number\n\n"; print "We will now print the square root of each number in the array a +s long as it falls between the range of 100-200 \n\n"; my @values = (); foreach $num (@number) { $sq = $num * $num; if ($sq >= 100 && $sq <= 200) { push(@values, $sq); } } print "Obtaining square values using foreach loop: @values\n";

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (16)
As of 2015-07-30 19:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (273 votes), past polls