There were several errors, but the main one was declaring a second @ten_array inside the loop. Others were:
- Initialising @ten_array with 0 which doesn't clear the array as I guess you were thinking, but assigns 0 as the first element
- Declaring square nested. It will not work as you expect
- 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.
- 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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.