Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: new to perl, need some help

by NetWallah (Canon)
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


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.

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://996796]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2018-06-19 11:07 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (113 votes). Check out past polls.