July 2002
Beginner to intermediate
432 pages
8h 55m
English
Listing 3.2 shows a program that reads a list of numbers from the user and creates an array out of them.
# Note: This program is inefficient
use strict;
use warnings;
my @array = (); # The list of numbers we have read
while (1) {
print "Input number or <Enter> to finish: ";
my $answer = <STDIN>;
chomp($answer);
if ($answer eq "") {
last;
}
@array = (@array, $answer);
}
|
The problem is the following line:
@array = (@array, $answer);
This takes the array @array and the scalar $answer and combines them into an array expression. This array expression is then assigned to @array. Because you are computing a new array and doing an entire replacement, this is inefficient.
A more efficient way of doing ...
Read now
Unlock full access