in reply to Storing 10 numbers in array

There were several errors, but the main one was declaring a second @ten_array inside the loop. Others were:

  1. Initialising @ten_array with 0 which doesn't clear the array as I guess you were thinking, but assigns 0 as the first element
  2. Declaring square nested. It will not work as you expect
  3. Assigning $number to @ten_array. Even if you hand't redeclared @ten_array that wouldn't have worked because it simply replaces any previous content of the array with a single element containing $number.
  4. You use $number as a global inside square, but you call square passing a value into it. Usage and implementation are not consistent.

A cleaned up version of your code with a few other changes is shown below. Note in particular the use of strict (always use strictures) and a Perl for loop to count the loop iterations instead of hand roling a while loop to do that.

#!/usr/bin/perl use strict; use warnings; my $wanted = 3; my @numbers; print "Enter $wanted numbers.\n"; for (1 .. $wanted) { my $number = <>; chomp($number); push @numbers, $number; square($number); } print "The ten numbers were @numbers\n"; sub square { my ($number) = @_; my $square_num = $number * $number; print "$number squared is: $square_num\n"; }
True laziness is hard work

Replies are listed 'Best First'.
Re^2: Storing 10 numbers in array
by CountZero (Bishop) on Mar 25, 2012 at 20:39 UTC
    Nitpicking, but to make your program perfect
    print "The ten numbers were @numbers\n";
    should be
    print "The $wanted numbers were @numbers\n";

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
Re^2: Storing 10 numbers in array
by snakeyes52 (Initiate) on Mar 25, 2012 at 21:41 UTC

    Many thanks for your enlightened solution!